y
05/01/2024, 7:53 AMif (this is Foo && this.bar is BarWithBaz) {
this.bar.baz // can't smart-cast, bar is an abstract val
} else {
/** some other baz */
}
is it frowned-upon/unidiomatic to do an unsafe cast here?Sam
05/01/2024, 7:59 AMval
doesn't have to return the same value on each access. Since it's abstract, the concrete class could provide an implementation that returns BarWithBaz
half the time, and something different the rest of the time.Sam
05/01/2024, 8:01 AM((this as? Foo)?.bar as? BarWithBaz)?.baz ?: someOtherBaz
I don't love all the parentheses though 😞y
05/01/2024, 8:04 AMy
05/01/2024, 8:06 AMRob Elliot
05/01/2024, 12:54 PMfun Any.asFoo() = this as? Foo
fun Bar.asBarWithBaz() = this as? BarWithBaz
this.asFoo()?.bar?.asBarWithBaz()?.baz ?: someOtherBaz
y
05/01/2024, 12:57 PM