JP Wang
07/02/2019, 6:22 AMserebit
07/02/2019, 6:25 AMorigin as? T isn't a safe cast at all, it's always going to be unsafeStephan Schroeder
07/02/2019, 9:01 AMtoInt() is for as in val i = "123".toInt()Stephan Schroeder
07/02/2019, 9:13 AMfun main() {
println("test")
val anyInt = 125 as Any
println (anyInt)
val backAsInt = cast<Int>(anyInt)
println(backAsInt)
}
inline fun <reified T> cast(origin: Any): T? = origin as? Tkarelpeeters
07/02/2019, 11:36 AMnull in this case. It works fine if you flip String and Int in the code.karelpeeters
07/02/2019, 11:36 AMJP Wang
07/02/2019, 5:19 PMint which will cause NullPointerException due to the Integer.toInt.serebit
07/02/2019, 5:26 PMnull, because you're casting to an erased type T. That's why the compiler complains about an unchecked castJP Wang
07/02/2019, 5:33 PMInteger? If you change the T: Int to such as T: Shape, it will print null. The whole point here is that it throws NPE which is not expected. If I’m not looking at the bytecode, I have no idea why it returns NPE - It throws NPE because the compiler makes the cast method to return int instead of Integer, then the NPE throws due to the Integer.toInt()JP Wang
07/02/2019, 5:34 PMas? operator always return you reference type? Does it make sense that optimizing the return type to primitive type?karelpeeters
07/02/2019, 5:38 PM