https://kotlinlang.org logo
Title
p

Peter

04/05/2023, 5:13 PM
does anyone know, if kotlin has extension function like this:
any.takeIf<Int>()
y

Youssef Shoaib [MOD]

04/05/2023, 5:35 PM
You can easily roll your own:
inline fun <reified T> Any.takeIf(): T? = if (this is T) this else null
p

Peter

04/05/2023, 5:44 PM
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

Gleb Minaev

04/05/2023, 6:56 PM
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 }
.