简体   繁体   中英

Kotlin array initialization throws null pointer exception

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM