【问题标题】:kotlin null pointer exception in default value默认值中的kotlin空指针异常
【发布时间】:2022-01-19 00:12:12
【问题描述】:

我有这样的代码:

@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 注入。

【问题讨论】:

  • 可以分享departmentClient.getById()的实现吗?对我来说,错误可能出在该函数中。它的返回值是一个不可为空的Department,尽管它可能找不到具有给定id 的部门,而是返回null。这可能发生在您使用 Jave 库搜索部门(例如在数据库中)并且在没有具有帽子 ID 的部门的情况下,该库返回 null。
  • 不,在实现中,它使用rest模板调用另一个微服务。如果它没有找到它会抛出一个异常。
  • 其余模板从何而来?

标签: kotlin nullpointerexception default-value


【解决方案1】:

函数getById 可能定义错误,并且在运行时遇到空指针异常。这个函数哪里来的?

应该是这样的:

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

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

【讨论】:

  • 请看评论。此函数不能抛出空指针。
  • 是“rest微服务”抛出的异常处理正确还是转换为departmentClient.getById调用返回的空值?
猜你喜欢
  • 2019-03-31
  • 2020-03-07
  • 1970-01-01
  • 1970-01-01
  • 2016-09-22
  • 2013-12-19
  • 2015-05-02
  • 1970-01-01
相关资源
最近更新 更多