Created
August 21, 2022 11:47
-
-
Save dvt32/54a6fdf1dcddb2cc241cdf97bd9a2b13 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* MUST: | |
* - be an extension function OR a member function | |
* - have a single parameter with no default value | |
* - have the "infix" keyword | |
*/ | |
infix fun Int.plus(that: Int) = this + that | |
// infix fun doStuff1() = println("blablabla") // COMPILER ERROR | |
// infix fun Int.doStuff2(a: Int, b: String) = println("blablabla") // COMPILER ERROR | |
// infix fun doStuff3(a: Int) = println("blablabla") // COMPILER ERROR | |
// infix fun Int.doStuff4(a: Int = 5) = println("blablabla") // COMPILER ERROR | |
class InfixExample { | |
// Makes code closer to natural language | |
fun test() { | |
val sum = 1 plus 1 | |
println(sum plus 20) | |
// "until" and "downTo" are also infix functions | |
for (i in 1 until 4) println(i) | |
for (i in 4 downTo 1) println(i) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment