Infix function with when - is it possible?
Infix function with when - is it possible?
is it possible to use infix function with when statement. Something similar to this:
infix fun Int.isGreater(value: Int): Boolean = this > value
and then:
when (value)
isGreater 2 -> doSomething()
isGreater 1 -> doSomethingElse()
else -> doNothing()
infix
I tried it, it doesn't work. I am just curious if there is any possibility to achieve this kind of structure
– Rafał Berkowicz
Aug 29 at 13:17
2 Answers
2
Actually: no, this will not work. The reason can be seen when consulting the when
grammar, which doesn't have a construct that takes the value given to when
and calls functions of the whenCondition
on it. So it doesn't have to do with the infix
itself (while it is true that it needs a receiver on the left).
when
when
whenCondition
infix
What you could do is the following:
when {
value isGreater 2 -> ...
value.isGreater(1) -> ...
If you like, you can also read more about when
in the Kotlin reference.
when
You cannot call infix functions like you do. It always needs a receiver on the left side:
when
value isGreater 2 -> doSomething()
value isGreater 1 -> doSomethingElse()
else -> doNothing()
Note that infix functions always require both the receiver and the parameter to be specified. When you're calling a method on the current receiver using the infix notation, you need to use this explicitly; unlike regular method calls, it cannot be omitted.
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Did you try it? Actually: no... this will not work, but that has nothing to do with the
infix
...– Roland
Aug 29 at 13:12