https://kotlinlang.org logo
Title
y

y

03/25/2023, 12:24 PM
how would I write
as?
as a function?
foo.tryAs(String)
=
foo as? String
s

Sam

03/25/2023, 12:31 PM
inline fun <reified T> Any.tryAs(): T? = this as? T
The angle brackets specify a type parameter. You call it like this.
foo.tryAs<String>()
For more explanation read this section of the docs: https://kotlinlang.org/docs/inline-functions.html#reified-type-parameters
y

y

03/25/2023, 12:34 PM
thanks a lot!
p

Paul Griffith

03/27/2023, 3:50 PM
you don’t need your own extension, KClass already has a safecast function so
foo::class.safeCast(bar)
(from an instance of foo)