fun main(args: Array) { testCast(Test(), true) testCast(null, false) testCastToNullable(null, true) println("Ok") } class Test fun ensure(b: Boolean) { if (!b) { println("Error") } } fun testCast(x: Any?, expectSuccess: Boolean) { try { x as T } catch (e: Throwable) { ensure(!expectSuccess) return } ensure(expectSuccess) } fun testCastToNullable(x: Any?, expectSuccess: Boolean) { try { x as T? } catch (e: Throwable) { ensure(!expectSuccess) return } ensure(expectSuccess) }