Kotlin数组初始化引发空指针异常 [英] Kotlin array initialization throws null pointer exception
问题描述
我是kotlin的初学者,我正在尝试使用接受大小和函数的构造函数初始化数组.这就是我所拥有的:
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?
我是原始海报的教授,我们正在努力使这一工作更加紧密.这是更多信息:
I'm the original poster's professor, and we're trying to get this working together. Here's some more info:
我已经将上面的代码编辑为完整程序.我们已在服务器上安装的Kotlin版本为:
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)
我会注意到,此代码对于在装有Kotlin较旧版本的笔记本电脑上进行编译就可以了.
I'll note that this code compiles just fine for me on my laptop, which has an older version of Kotlin.
推荐答案
这是一个错误在Kotlin编译器的AOT编译(取决于OS)版本中.请查看该问题以获取更新.
This is a bug in the AOT-compiled (OS-dependent) version of the Kotlin compiler. Please see the issue for updates.
这篇关于Kotlin数组初始化引发空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!