线程“ main”中的异常java.lang.IllegalArgumentException:指定为非null的参数为null:方法UserModel.getValue,参数接收器$ 0 在UserModel.getValue(DelegateTest2.kt) 在UserModel.getAge(DelegateTest2.kt)
fun main() {
val user = UserModel(hashMapOf("profession" to "abc", "age" to 10))
println("user: $user")
println("userInfo: " + user.userInfo)
println(user.age)
println("User from Json")
val resp = "{\"userInfo\":{\"age\":10, \"profession\":\"abc\"}}"
val userFromJson = Gson().fromJson(resp, UserModel::class.java)
println("user: $userFromJson")
println("userInfo: ${userFromJson.userInfo}")
println(userFromJson.age)
}
data class UserModel(val userInfo: HashMap<String, Any?>) : Serializable {
private operator fun <V> MutableMap<in String, in V?>.getValue(thisRef: Any?, property: KProperty<*>): V? {
println("get ${property.name}")
@Suppress("UNCHECKED_CAST")
return getOrDefault(property.name, null) as V?
}
private operator fun <V> MutableMap<in String, in V?>?.setValue(ref: Any?, property: KProperty<*>, value: V?) {
println("set ${property.name} $value")
this?.put(property.name, value)
}
var profession: String? by userInfo
var age: Int? by userInfo
}
日志:
user: UserModel(userInfo={profession=abc, age=10})
userInfo: {profession=abc, age=10}
get age
10
User from Json
user: UserModel(userInfo={profession=abc, age=10.0})
userInfo: {profession=abc, age=10.0}
Exception in thread "main" java.lang.IllegalArgumentException: Parameter specified as non-null is null: method UserModel.getValue, parameter receiver$0
at UserModel.getValue(DelegateTest.kt)
at UserModel.getAge(DelegateTest.kt)