Search code examples
mongodbspring-bootkotlinnull

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


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?


Solution

  • 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.