从Kotlin调用具有可为空变量的Java函数在Spring Boot / Mongodb中无法正常工作。

huangapple go评论81阅读模式
英文:

Calling Java function with nullable variable from Kotlin not working in Spring Boot / Mongodb

问题

我正在尝试在Spring Boot和Kotlin中使用mongoTemplate和Criteria API(https://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/core/query/Criteria.html)创建一个MongoDB查询。出于某种原因,当我尝试调用期望非空参数的方法时,代码正常工作。例如:

query.addCriteria(Criteria.where("age").lt(50))

正常工作。这是因为lt方法(请参阅上面的文档)期望非空参数,我猜是这个原因。然而,当我改为执行以下操作时:

query.addCriteria(Criteria.where("name").is("Bob"))

我得到了异常“Expecting an element”。我查看了文档,发现is方法期望一个可空参数,而不是非空参数,似乎这是导致引发异常和不引发异常的方法之间的模式(例如,gte()也不会引发异常)。

从Kotlin中如何使用is()方法,该方法是用Java编写的,期望一个可空参数?

英文:

I am trying to create a MongoDB query in Spring boot and Kotlin by using mongoTemplate and the Criteria API (https://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/core/query/Criteria.html) , which is written in Java. For some reason when I try to call a method that expects a non null parameter, the code works fine. For example:

query.addCriteria(Criteria.where("age").lt(50))

works fine. This is because the lt method (see documentation above) expects a non null parameter I am guessing. However, when I instead do

query.addCriteria(Criteria.where("name").is("Bob"))

I get the exception "Expecting an element" . I looked at the documentation and the is method expects a nullable parameter instead of a non null parameter, and this distinction seems to be the pattern between methods that cause an exception and those that don't (for example, gte() also doesn't cause an exception).

From Kotlin, how do I use the is() method, which is written in Java and expects a nullable parameter?

答案1

得分: 3

is 不是 Java 中的关键字,但在 Kotlin 中是关键字。is 是 Kotlin 中的类型检查运算符。

在 Kotlin 中,当你调用 is 时,应该使用反引号进行转义。

query.addCriteria(Criteria.where("name").`is`("Bob"))

根据语言规范:

Kotlin 支持将标识符括在反引号 (`) 字符中,允许将任何字符序列用作标识符。这不仅允许在名称中使用非字母数字字符(如 @ 或 #),还允许将关键字(如 if 或 when)用作标识符。

英文:

is is not a keyword in Java, but it is in Kotlin. is is the type-check operator in Kotlin.

You should escape is with backticks when you are calling it in Kotlin.

query.addCriteria(Criteria.where("name").`is`("Bob"))

From the language spec:

> Kotlin supports escaping identifiers by enclosing any sequence of
> characters into backtick (`) characters, allowing to use any name as
> an identifier. This allows not only using non-alphanumeric characters
> (like @ or #) in names, but also using keywords like if or when as
> identifiers.

huangapple
  • 本文由 发表于 2023年7月6日 12:22:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76625482.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定