[英]kotlin null pointer exception in default value
我有这样的代码:
@Service
class SomeClass (
private val departmentClient : DepartmentClient
) {
fun someFunction(
employee: Employee,
department: Department = departmentClient.getById(employee.departmentId)
): Unit {
here my code
}
}
data class Employee(val departmentId: Long, val id: Long)
data class Department(val id: Long)
@Service
class DepartmentClient() {
fun getById(id: Long): Department
}
当我不在 someFunction 中传递 department 参数时,我希望departmentClient.getById(employee.departmentId)
将被调用。 问题是,在某些情况下,我会在这一行中得到 null 指针异常,但在其他情况下,我不会。 所有依赖都是通过Spring注入的。
function getById
可能定义错误,并且在运行时遇到空指针异常。 这个function是哪里来的?
它应该如下所示:
class DepartmentClient() {
fun getById(id: Long): Department?
}
那将意味着您需要与department: Department?
在here my code
。
我认为当您分配一个变量 null 值时会发生这种情况 您可以通过使用“?”来解决这样的问题或者 '?。' (安全操作员)通过输入“?” 在类型(部门)之后
fun someFunction(
employee: Employee,
department: Department? = departmentClient.getById(employee.departmentId)
): Unit {
here my code
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.