Kotlin array initialization throws null pointer ex

2019-07-26 07:27发布

问题:

I'm a total beginner with kotlin, and I'm trying to initialize an array using the constructor that accepts a size and a function. This is what I have:

fun main(args: Array<String>) {
    var ary = Array(5, {x -> x + 2})
    println(ary[2])
}

But it's throwing a null pointer exception on the first line. Why is this happening?


EDIT: I'm the original poster's professor, and we're trying to get this working together. Here's some more info:

I've edit the code above to be the full program. The version of Kotlin we have installed on our server is:

$ kotlinc -version
info: kotlinc-jvm 1.2.70 (JRE 1.8.0_144-jdk_2017_08_24_20_46-b00)

When I try to compile and run from the command line I get:

$ kotlinc example.kt -include-runtime -d example.jar
$ java -jar example.jar 
Exception in thread "main" java.lang.NullPointerException
    at ExampleKt.main(example.kt:2)

I'll note that this code compiles just fine for me on my laptop, which has an older version of Kotlin.

回答1:

This is a bug in the AOT-compiled (OS-dependent) version of the Kotlin compiler. Please see the issue for updates.



标签: kotlin