hfhbd
11/12/2022, 1:54 PMsealed class F {
object A: F()
object B: F()
}
fun F.foo(): F = when (this) {
is F.A -> F.A
is F.B -> F.B
}
val a: F.A = F.A.foo() // not possible without a cast
Ruckus
11/12/2022, 4:11 PMfun <T : F> T.foo(): T = this
Ruckus
11/12/2022, 4:16 PMobject
, my code will do exactly what you asked. If there are classes, however, you need to tell Kotlin how to create an instance (either via reflection, or by passing another parameter).hfhbd
11/12/2022, 4:41 PMfoo
to the subclass of the sealed class.hfhbd
11/12/2022, 4:42 PMsome F
in SwiftYoussef Shoaib [MOD]
11/13/2022, 8:50 AMsealed class F<Self : F<Self>> {
object A: F<A>() {
override fun foo(): A {
//do something
return this
}
}
object B: F<B>() {
override fun foo(): B {
//do something
return this
}
}
abstract fun foo(): Self
}
Youssef Shoaib [MOD]
11/13/2022, 8:53 AMfun <T: F> T.foo(): T {
when (this) {
is F.A -> // do something for A
is F.B -> // do something for B
else -> {} // compiler is stupid, so an else is required
}
return this
}
Basically, if you need to create a new instance of T, you'll need some reflection mechanism or some function that's defined to return the Self type, but otherwise, you're safe to do whatever you want and simply return the passed-in valuehfhbd
11/13/2022, 9:38 AMsealed class F {
data class A(val a: Int) : F()
data class B(val b: Int) : F()
}
fun <T : F> T.foo(): T = when (this) {
is F.A -> copy(a = a + a)
is F.B -> copy(b = b + b)
else -> error("not possible")
} // as T
val a: F.A = F.A(1).foo()
hfhbd
11/13/2022, 9:39 AMYoussef Shoaib [MOD]
11/13/2022, 9:51 AMfoo
function since you know that it's safe. The issue is that Kotlin doesn't unite the type T
with F.A when it knows that this is an F.A. There isn't much you can do here sadly unless you can edit the base sealed class and add a copy method to it