简体   繁体   English

kotlin null 默认值指针异常

[英]kotlin null pointer exception in default value

I have code like this one:我有这样的代码:

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

When I don't pass the department parameter in someFunction, I expect that departmentClient.getById(employee.departmentId) will be called.当我不在 someFunction 中传递 department 参数时,我希望departmentClient.getById(employee.departmentId)将被调用。 The problem is that in some cases I get a null pointer exception in this line, but in others, I don't.问题是,在某些情况下,我会在这一行中得到 null 指针异常,但在其他情况下,我不会。 All dependencies are injected by Spring.所有依赖都是通过Spring注入的。

The function getById is probably defined wrongly and at runtime it hits with a null-pointer-exception. function getById可能定义错误,并且在运行时遇到空指针异常。 Where does this function come from?这个function是哪里来的?

It should look like this:它应该如下所示:

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

That would mean you need to deal with department: Department?那将意味着您需要与department: Department? in here my code .here my code

I think this happens when You assigned a variable null value You can fix the problem like this by using '?'我认为当您分配一个变量 null 值时会发生这种情况 您可以通过使用“?”来解决这样的问题or '?.'或者 '?。' (safety operator) by putting '?' (安全操作员)通过输入“?” after a Type (Department)在类型(部门)之后

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

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

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