Last active
November 3, 2022 09:00
-
-
Save muhammedesadcomert/ff42533cdc530a12744327638bbc79b7 to your computer and use it in GitHub Desktop.
Infix functions in Kotlin
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
/* | |
* In Kotlin, a functions marked with infix keyword can also be called using | |
* infix notation means calling without using parenthesis and dot. | |
*/ | |
// Call using dot and parenthesis | |
var result1 = a.shr(1) | |
// Call using infix notation | |
var result2 = a shr 2 | |
// User defined infix member function | |
infix fun dataType(x: Any): Any { | |
var i = when(x) { | |
is String -> "String" | |
is Int -> "Integer" | |
is Double -> "Double" | |
else -> "invalid" | |
} | |
return i | |
} | |
/* | |
* This is most commonly seen in the inline Map definition. | |
* "to" might look like a special keyword but in this example, | |
* this is a to() method leveraging the infix notation and returning a Pair<A, B>. | |
*/ | |
map( | |
1 to "one", | |
2 to "two", | |
3 to "three" | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment