简体   繁体   中英

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. The problem is that in some cases I get a null pointer exception in this line, but in others, I don't. All dependencies are injected by Spring.

The function getById is probably defined wrongly and at runtime it hits with a null-pointer-exception. Where does this function come from?

It should look like this:

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

That would mean you need to deal with department: Department? in here my code .

I think this happens when You assigned a variable null value You can fix the problem like this by using '?'or '?.' (safety operator) by putting '?' after a Type (Department)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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