【问题标题】:Classifier does not have a companion object , and thus must be initialized here分类器没有伴随对象,因此必须在此处初始化
【发布时间】:2019-12-29 11:20:17
【问题描述】:

伙计们,我对 kotlin 和 spring 很陌生。如果记录不存在,我试图抛出 exepiion。我不知道如何包装这一行的语法。 所以这是我的例外类:

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "Record not found")
class NotFound : Exception()

这是我的代码:

fun getUserById(userId: Int): User {
        return User(userRepository!!.findById(userId).orElse(ExeptionClass))//So the problem appears here
    }

所以它说:分类器 ExeptionClass 没有伴生对象,因此必须在这里初始化

【问题讨论】:

  • 什么是ExeptionClass?你想达到什么目的?
  • 当我尝试获取不存在的 ID 时,我希望出现异常。
  • 离题:Java 的 Optional 在 Kotlin 中没用,最好在你的 repo 中创建一个方法:fun findById(id:Int): User?。然后只使用可空类型而不是可选类型:repo.findById(id) ?: ExeptionClass()。另外要摆脱那些!!,您必须通过使用不可为空类型的构造函数注入 repo。

标签: java spring kotlin


【解决方案1】:

所以你想抛出一个异常。因此,您想使用orElseThrow(),而不是orElse()

因此,您需要通过调用其构造函数来传递创建并返回异常的供应商(即lambda)。异常被命名为NotFound,而不是ExeptionClass。所以代码应该是

return User(userRepository!!.findById(userId).orElseThrow { NotFound() })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-01
    • 2019-03-15
    • 2019-04-27
    • 1970-01-01
    • 2019-01-20
    • 2021-11-23
    • 2019-07-23
    • 1970-01-01
    相关资源
    最近更新 更多