'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?
Solution 1:[1]
Thanks to Raphael's answer I was able to find out that
- Instead of Kotlin's
isthere's Java'sinstanceof. - SpEL has a special syntax for using
instanceofwhere you need to use a wrapper around the class:filterObject instanceof T(YourClass). - The fully qualified class name must be used for classes from any other package than
java.lang. - 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 wasnet.goout.feed.model.Target$User.
Putting all this together yeilds this SpEL
#target instanceof T(net.goout.feed.model.Target$User)
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Raphael Tarita |
