marschwar
08/08/2018, 2:49 PMsealed 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
?uhe
08/08/2018, 3:17 PMis
with generics because of type erasure that's probably never gonna work. (Unless the smart-caster gets way smarter)reified
stuff, which lead me to above post)Can Orhan
08/08/2018, 3:25 PMsealed 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 criticismmarschwar
08/08/2018, 3:57 PMdoSomething
. 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.
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
Can Orhan
08/08/2018, 5:39 PM