what's the syntax for checking type and then using...
# announcements
t
what's the syntax for checking type and then using typed object? kind of like a
.let<Type> { }
Copy code
val something: X
fun f() {
	if (something is Y) {
		(something as Y).g()
	}
}
I see two options:
Copy code
val something: X
fun f() {
	val cacheOfSomething = something
	if (cacheOfSomething is Y) {
		(cacheOfSomething as Y).g()
	}
}
or
Copy code
(something as? Y)?.g()
neither of which is pleasing, any other way to do this?
a
If you have
(something is Y)
you should be able to smartcast inside of that block, no?
👆 3
d
you don't need to cast it with as if you are in the scope of the if x is y check
a
if (thing is String) { println(thing.length) }
âž• 2
t
oh, sorry, the val is outside the scope of the funciton, it could change value over time (custom getter) the
as Y
is not showing as redundant
a
ooo
Well sometimes I'll do
(something as? MyClass)?.let { ... }
which would work in your example I believe
t
something.takeIf { it is Y }?.let { it.g() }
😬 1
a
Robert, what about
(something as? Y)?.g()
wasn't preferable to you? I think it's the most idiomatic way to accomplish what you're trying to do.
t
or i guess drop the let block.
something.takeIf { it is Y }?.g()
one bonus of using
is
is that the ide can tell you the check for instance is always true/false.
t
@trevjones I like
takeIf
, but I'm trying to call
Y.g()
, not
X.g()
😞 (
takeIf
is not aware of cast) @adam-mcneilly it introduces null to the mix, even though there's nothing nullable going on in the expression, it's just a simple non-null typecheck+cast.
t
perhaps this:
Copy code
inline fun <reified T, R: Any> Any?.takeAs(crossinline block: (T) -> R?): R? {
  return if (T::class.java.isInstance(this)) block(this as T) else null
}
something.takeAs<Y> { it.g() }
t
yep, just got to a similar conclusion:
Copy code
inline fun <reified T> Any.run(crossinline block: T.() -> Unit) {
	if (this is T) { block(this) }
}
note: you can do
this is T
on reified no need for explicit reflection.
t
yea I just like the
isInstance
because I can hit F1 on it and get a spew of documentation
🤔 1