fun Any?.unsafeCast(): T = this as T fun foo(returnType: String): R { return when { returnType == "Nothing" -> throw Exception() else -> null.unsafeCast() } } fun box(): String { foo("") return "OK" }