简体   繁体   English

空指针异常与地图一起使用(Kotlin)

[英]Null Pointer Exception working with Map (Kotlin)

I have the following class: 我有以下课程:

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)
    }

class Entry looks like this: 类Entry看起来像这样:

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

Main: 主要:

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

When I run the program and try using the "define" function I get the following error: 当我运行程序并尝试使用“定义”功能时,出现以下错误:

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)

I assume the problem has something to do with how I create a new symbolTable class, but seeing as Kotlin doesn't have "new" I don't know how to avoid the null pointer exception. 我认为问题与我如何创建新的symbolTable类有关,但是由于Kotlin没有“ new”,我不知道如何避免空指针异常。

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

This doesn't make much sense: you test if the value is 0, and if it is, you set it to 0. So it's basically a noop. 这没有多大意义:您测试值是否为0,如果为0,则将其设置为0。因此,它基本上是noop。

What you want is to test if the value is null: 您想要测试值是否为空:

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

You could also avoid using the dangerous !! 您也可以避免使用危险!! operator by saving the value into a variable. 运算符,方法是将值保存到变量中。

And you should really use val rather than var: all of your fields shouldn't be mutable: 而且您应该真正使用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")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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