Jen
Jen

Reputation: 1338

How to use Kotlin's `is` operator in SpEL expression?

I have a simple sealed class

sealed class Target {
    class User(val id: Long) : Target()
    class City(val id: String) : Target()
}

that is used as a parameter of s Spring bean method. I'd like to cache the method via the @Cacheable conditionally only when the parameter is User.

@Cacheable(CACHE_NAME, condition = "#target is Target.User")
open fun getFeed(target: Target): Map<String, Any?> { ... }

However I get an error: '(' or <operator> expected, got 'is'

How can I use is in the condition string?

Upvotes: 0

Views: 727

Answers (2)

Jen
Jen

Reputation: 1338

Thanks to Raphael's answer I was able to find out that

  1. Instead of Kotlin's is there's Java's instanceof.
  2. SpEL has a special syntax for using instanceof where you need to use a wrapper around the class: filterObject instanceof T(YourClass).
  3. The fully qualified class name must be used for classes from any other package than java.lang.
  4. The fully qualified name available on runtime for a class defined inside the body of a sealed class is <package>.<SealedClass>$<SubClass>. In my case it was net.goout.feed.model.Target$User.

Putting all this together yeilds this SpEL

#target instanceof T(net.goout.feed.model.Target$User)

Upvotes: 2

Raphael Tarita
Raphael Tarita

Reputation: 942

As far as I know, SpEL is java-based, and Java does not have an operator called 'is'. The Java equivalent of 'is' is 'instanceof'. Since Java and Kotlin are interoperable and you can work with Kotlin classes in a Java context, #target instanceof FeedTarget.User should work fine.

Upvotes: 1

Related Questions