使用Map(Kotlin)的空指针异常

时间:2016-06-05 07:33:03

标签: kotlin kotlin-null-safety

我有以下课程:

class SymbolTable(){
    var map = mutableMapOf<String, Entry>()
    var kindCounter = mutableMapOf<String, Int>()

    fun define(name:String, kind:String, type:String){
        if(kindCounter[kind]==0){
            kindCounter[kind]=0
        }
        var index = 1
        map[name]= Entry(type, kind, index)
        kindCounter[kind]=kindCounter[kind]!!.plus(1)
    }

类Entry看起来像这样:

class Entry(var type:String, var kind:String, var index:Int)

主:

fun main(args:Array<String>){
    var example = SymbolTable()
    example.define("ex1", "ex1", "ex1")
    example.define("ex2", "ex2", "ex2")
}

当我运行程序并尝试使用&#34;定义&#34;功能我收到以下错误:

Exception in thread "main" kotlin.KotlinNullPointerException
    at SymbolTable.define(SymbolTable.kt:21)
    at SymbolTableKt.main(SymbolTable.kt:31)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

我认为问题与我如何创建一个新的symbolTable类有关,但看到Kotlin没有&#34; new&#34;我不知道如何避免空指针异常。

1 个答案:

答案 0 :(得分:2)

if(kindCounter[kind]==0){
   kindCounter[kind]=0
}

这没有多大意义:你测试的是值是0,如果是,你将它设置为0.所以它基本上是一个noop。

您想要测试的值是否为null:

if (kindCounter[kind] == null) {
   kindCounter[kind] = 0
}

您还可以通过将值保存到变量中来避免使用危险的!!运算符。

你应该使用val而不是var:你的所有字段都不应该是可变的:

class SymbolTable() {
    val map = mutableMapOf<String, Entry>()
    val kindCounter = mutableMapOf<String, Int>()

    fun define(name: String, kind: String, type: String) {
        val count = kindCounter[kind] ?: 0
        map[name] = Entry(type, kind, 1)
        kindCounter[kind] = count + 1
    }
}

class Entry(val type: String, val kind: String, val index: Int)

fun main(args:Array<String>) {
    val example = SymbolTable()
    example.define("ex1", "ex1", "ex1")
    example.define("ex2", "ex2", "ex2")
}