https://kotlinlang.org logo
#compiler
Title
# compiler
r

rocketraman

04/17/2020, 7:58 PM
Poll: what should (note: not, what does) this code produce? (Hint: it produces 1️⃣ in Kotlin 1.4-dev with new inference enabled)
Copy code
fun <T> foo(): T? = "abc" as T

fun main() {
  val s: String? = if(false) null else foo()
}
1️⃣ A runtime exception
ClassCastException: class java.lang.String cannot be cast to java.lang.Void
2️⃣ A compile-time error due to the type
T
of
foo
being ambiguous (could be
String?
or could be
Nothing
) 3️⃣ A compile-time warning that the type of
T
was inferred to
Nothing
and that is probably not the desired result 4️⃣ An inference of
T
to be
String?
, so no compile-time or runtime errors 5️⃣ Other
2️⃣ 3
4️⃣ 5
Related fun fact:
Copy code
fun <T> bar(): T = "abc" as T

fun main() {
  val s: String? = if(false) null else bar()
}
produces a runtime exception 1️⃣, but at least it comes with a compile time warning 3️⃣.
m

mikhail.zarechenskiy

04/23/2020, 10:54 AM
See https://youtrack.jetbrains.com/issue/KT-36776 for more details, I believe we'll end up with the 4️⃣ for cases like that
👍 1
2 Views