默认值中的Kotlin空指针异常

uyto3xhc  于 2023-01-31  发布在  Kotlin
关注(0)|答案(2)|浏览(129)

我有这样的代码:

@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)会被调用,问题是在某些情况下,我在这一行中得到一个空指针异常,但在其他情况下,我没有,所有的依赖都是由Spring注入的。

guicsvcw

guicsvcw1#

函数getById可能定义错误,在运行时遇到空指针异常。这个函数来自哪里?
它应该如下所示:

class DepartmentClient() {
    fun getById(id: Long): Department?
}

这意味着您需要在here my code中处理department: Department?

tct7dpnv

tct7dpnv2#

我认为当你分配一个变量空值时会发生这种情况。你可以通过使用“?”或“?.”(安全操作符),在类型(部门)后放置“?”来解决这样的问题。

fun someFunction(
        employee: Employee,
        department: Department? = departmentClient.getById(employee.departmentId)
    ): Unit {
        here my code
    }

相关问题