Infix Functions in Kotlin

Bringing our code closer to natural language

Arturo Gutiérrez
Mar 17, 2017 · 2 min read
enum class Suit {
HEARTS,
SPADES,
CLUBS,
DIAMONDS
}
enum class Rank {
TWO, THREE, FOUR, FIVE,
SIX, SEVEN, EIGHT, NINE,
TEN, JACK, QUEEN, KING, ACE
}
data class Card(val rank: Rank, val suit: Suit)
val card = Card(Rank.QUEEN, Suit.HEARTS)
enum class Rank {
TWO, THREE, FOUR, FIVE,
SIX, SEVEN, EIGHT, NINE,
TEN, JACK, QUEEN, KING, ACE;
fun of(suit: Suit) = Card(this, suit)
}
val card = Rank.QUEEN.of(Suit.HEARTS)
val card = QUEEN.of(HEARTS)
enum class Rank {
TWO, THREE, FOUR, FIVE,
SIX, SEVEN, EIGHT, NINE,
TEN, JACK, QUEEN, KING, ACE;

infix fun of(suit: Suit) = Card(this, suit)
}
val card = QUEEN of HEARTS


Making Tuenti

Sharing the daily awesomeness of making Tuenti

Thanks to Juan Cazalla.

Arturo Gutiérrez

Written by

Software Engineer at @47deg | arturogutierrez.com

Making Tuenti

Sharing the daily awesomeness of making Tuenti