Hi, after trying for several hours, I could really...
# getting-started
m
Hi, after trying for several hours, I could really use some help.
Copy code
sealed class MyTypes

class A : MyTypes()
class B : MyTypes()

class Wrapper<out T : MyTypes>(val wrapped: T)

val wrappedValue: Wrapper<MyTypes> = Wrapper(A())

val nothing = when (wrappedValue.wrapped) {
    is A -> doSomethingWithA(wrappedValue as Wrapper<A>)
    is B -> doSomethingWithB(wrappedValue as Wrapper<B>)
}

fun doSomethingWithA(a: Wrapper<A>) = Unit
fun doSomethingWithB(b: Wrapper<B>) = Unit
Is there any way I can get rid of the unchecked cast within the
when
?
u
I don't see how. According to https://stackoverflow.com/a/38859036: "A smart cast is applied to a specific object after you use is to check its type or compare it with null. " Since you can't use
is
with generics because of type erasure that's probably never gonna work. (Unless the smart-caster gets way smarter)
(I tried to make it work by applying some
reified
stuff, which lead me to above post)
c
Is something like this perhaps more suitable?
Copy code
sealed class MyTypes{
    class A : MyTypes()
    class B : MyTypes()
}

class Wrapper<out T : MyTypes>(val wrapped: T)

val wrappedValue: Wrapper<MyTypes> = Wrapper(MyTypes.A())

val nothing = when (wrappedValue.wrapped) {
    is MyTypes.A -> wrappedValue.wrapped.doSomethingWith()
    is MyTypes.B -> wrappedValue.wrapped.doSomethingWith()
}

fun MyTypes.A.doSomethingWith() = Unit
fun MyTypes.B.doSomethingWith() = Unit
^Open to criticism
m
Thank you guys. @Can Orhan Unfortunately this does not really help since I have properties in the wrapper I need to access inside
doSomething
. I opted for passing both the wrapper as well as the wrapped value. This way I can use the smart cast and still use properties of the wrapper.
Copy code
val nothing = when (wrappedValue.wrapped) {
    is A -> doSomethingWithA(wrappedValue, wrappedValue.wrapped)
    is B -> doSomethingWithB(wrappedValue, wrappedValue.wrapped)
}

fun doSomethingWithA(wrapper: Wrapper<*>, a: A) = Unit
fun doSomethingWithB(wrapper: Wrapper<*>, b: B) = Unit
c
Ahh ok! Thanks for sharing your solution 🙂