Kotlin Infix函数的使用方法
2018-08-17 本文已影响13人
假装在去天使之城的路上
假设你有一副扑克牌,你是这样定义的
//花形
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)
但是,如果你用了infix的话:
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
代码出自:
https://medium.com/makingtuenti/infix-functions-in-kotlin-2db3d3142dd2