Can cast operators be overloaded to support safe c...
# announcements
s
Can cast operators be overloaded to support safe casting of known types (conditionally)? I have a lot of factories for wrapper types (do some additional validation on the input, and return
Type?
), but it would be kind of cool to replace those with
as?
directly.
d
No,
as
will only check actual types. You can do something like this though to make it explicit:
Copy code
interface IsDisguise {
    fun <T : Any> unpack(cls: KClass<T>): T?
}

inline fun <reified R : Any> Any?.unpack(): R? {
    return this as? R ?: (this as? IsDisguise)?.unpack(R::class)
}
s
Yeah that's what I was thinking. It's not a big deal, but was just curious
l
Is there a feature request for
as
and
is
overloads?
d
I am not sure how they would work. Kotlin would have to compile every
as
and
is
use to a method call which does some "magic" instead of just an
instanceof
or
cast
JVM instruction. That would certainly come with performance problems
Plus, that goes against Kotlin's main design goal of being explicit about things, in my opinion. If you want more than a simple "is-a" check, don't use
is
and
as