Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dvt32/54a6fdf1dcddb2cc241cdf97bd9a2b13 to your computer and use it in GitHub Desktop.
Save dvt32/54a6fdf1dcddb2cc241cdf97bd9a2b13 to your computer and use it in GitHub Desktop.
/**
* 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