【问题标题】:kotlin specification nulablekotlin 规范可以为空
【发布时间】:2019-01-05 06:01:33
【问题描述】:

我正在尝试将 Spring Boot 2.0.3 与 IntelliJ IDEA 一起使用。 Kotlin 版本是 1.2.51。

当我使用 jsr305=strict 编译选项时,whereand 部分出现错误。

import com.example.spring_boot.domain.task.Task
import org.springframework.data.jpa.domain.Specification

object TaskSpecification {
    private fun nameContain(name: String?): Specification<Task>? {
        return name?.let {
            Specification { root, query, cb ->
                cb.like(root.get<String>("name"), name)
            }
        }
    }

    fun createSearchSpecification(name: String?
    ): Specification<Task> {
        return Specification.
            where(nameContain(name)).and(nameContain(name))
    }
}

它说“类型不匹配:必需:规范,找到:规范?”, 当我将它们更改为where(nameContain(name)!!)and(nameContain(name))!! 时,错误消失了。

然后我有一个问题。 我看到了 2 个方法声明。 whereand 这两种方法的参数看起来都不是 NotNull 类型。 为什么我会收到这样的错误?

在这里,我附上了声明图片。

,

【问题讨论】:

    标签: spring spring-boot kotlin


    【解决方案1】:

    您的nameContain(String?) 返回Specification&lt;Task&gt;?(可为空),这不是where(Specification&lt;T&gt;)(不可为空)的有效参数。

    使用return name?.let {... } 意味着如果name 为空,您的函数将返回null

    【讨论】:

    • 为什么Specification&lt;Task&gt;?不是有效参数?根据where 声明,该参数看起来可以为空。没有注释@Nonnull@NotNull
    • @KenjiOtsuka 也许与您的strict 标志有关?我对这个编译选项了解不多,但也许它强制所有非注释参数为非空值?如果可以修改where方法,在参数中添加@Nullable看是否修复。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-27
    相关资源
    最近更新 更多