Unless parameter T is reified, it’s treated as Any, so basically you wrote the following function: fun cast(from: Any): Any? = from as? Any
. Obviously it works for anything and compiler adds a different check at call site which throws exception. Basically that’s limitation of type erasure inherited from JVM. In Java you would pass Class<T>
instance, in Kotlin you can do the same or use reified modifier which will do the same under the hood,