https://kotlinlang.org logo
r

Robert Jaros

02/24/2020, 10:51 PM
Can this be fixed with some kind of casting? https://pl.kotl.in/OTh5QtrfF
other then
a as String
d

Dominaezzz

02/24/2020, 10:59 PM
a as Any
?
s

streetsofboston

02/24/2020, 10:59 PM
Copy code
inline fun <reified T: Any>test1(a: T?): Unit {
    if (a!=null) {
		test2(a)        
    }
}
d

Dominaezzz

02/24/2020, 11:00 PM
Also ☝🏼
s

streetsofboston

02/24/2020, 11:01 PM
This still trips me up that although even when
T
is bound to
Any?
, the type-inference can’t cast to to an upper bound to
Any
after a null-check…. It requires a bit of gymnastics…..
d

Dominaezzz

02/24/2020, 11:02 PM
With the new type inference?
s

streetsofboston

02/24/2020, 11:14 PM
Not sure if it is the new one or the old one… let me find an example….
Copy code
abstract class State<S, out A> {
    /**
     * Runs this [State]'s computation.
     *
     * It returns a (modified) state of type [S] with a result of this computation of type [A].
     */
    internal abstract val run: (S) -> Pair<S, A>
}

class StateFx<S> {
    private var currentState: S? = null

    fun <B> State<S, B>.bind(): B {
        val (newState, b) = <mailto:this@bind.run|this@bind.run>(currentState)
        currentState = newState

        return b
    }
}
In the above example,
<mailto:this@bind.run|this@bind.run>(currentState)
shows a compiler error for currentState: Required S, found S? If I change the currentState as follows,
private var currentState: S = null
, then this shows an error: Null cannot be a value of non-null type S Even though S has upper-bound `Any?`…..
(you can ‘fix’ it by calling
<mailto:this@bind.run|this@bind.run>(currentState as S)
)
b

bbaldino

02/24/2020, 11:50 PM
i ran into a similar problem when detecting something as an enum and then trying to handle it...because enums require a different upper bound on the type (
<T : Enum<T>>
). couldn't find any way to coerce it...I think even a cast there didn't work, but maybe i'm misremembering
k

Kroppeb

02/25/2020, 9:53 AM
6 Views