how would I write `as?` as a function? `foo.tryAs(...
# getting-started
y
how would I write
as?
as a function?
foo.tryAs(String)
=
foo as? String
s
Copy code
inline fun <reified T> Any.tryAs(): T? = this as? T
The angle brackets specify a type parameter. You call it like this.
Copy code
foo.tryAs<String>()
For more explanation read this section of the docs: https://kotlinlang.org/docs/inline-functions.html#reified-type-parameters
y
thanks a lot!
p
you don’t need your own extension, KClass already has a safecast function so
foo::class.safeCast(bar)
(from an instance of foo)