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()





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


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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế