does anyone know, if kotlin has extension function...
# getting-started
p
does anyone know, if kotlin has extension function like this:
Copy code
any.takeIf<Int>()
y
You can easily roll your own:
Copy code
inline fun <reified T> Any.takeIf(): T? = if (this is T) this else null
👍 1
p
Hm, maybe
takeIf
mislead me a bit. I guess
as?
is perfectly ok. I'm using it like so:
(any as? User)?.id
I guess doing
any.takeIf<User>()?.id
doesn't really make it more readable.
g
I opened corresponding issue some time ago. Because I needed the extension for chained calls. But it was closed in favour of future improved contracts that will infer the result type in
.takeIf { it is MyType }
.
👍 2