```if (this is Foo && this.bar is BarWithB...
# getting-started
y
Copy code
if (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?
s
Well the key is that it's unsafe 😄. A
val
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.
Maybe you could do something like this:
Copy code
((this as? Foo)?.bar as? BarWithBaz)?.baz ?: someOtherBaz
I don't love all the parentheses though 😞
y
I especially don't like the parenteheses because of https://kotlinlang.slack.com/archives/C0B8MA7FA/p1714398908780469
I guess Kotlin gives me plenty of tools here to avoid the explicit cast, so I'll use that even if bugs me aesthetically (I wish I cared less about this sort of things)
r
I probably overuse extension functions for parenthesis avoidance, but you can of course do:
Copy code
fun Any.asFoo() = this as? Foo
fun Bar.asBarWithBaz() = this as? BarWithBaz

this.asFoo()?.bar?.asBarWithBaz()?.baz ?: someOtherBaz
y
@Rob Elliot please see what I linked, this is "unsafe" so I stopped using functions like this
👍 1