我有以下课程:
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(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")
}
当我运行程序并尝试使用“定义”功能时,我收到以下错误:
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 没有“新”,我不知道如何避免空指针异常。