[英]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.