如果你想要坚持Schala的不可改变的风格,你就可以用不可改变的语种创建自己的班子:
class CountMap protected(val counts: Map[String, Int]){
def +(str: String) = new CountMap(counts + (str -> (counts(str) + 1)))
def apply(str: String) = counts(str)
}
object CountMap {
def apply(counts: Map[String, Int] = Map[String, Int]()) = new CountMap(counts.withDefaultValue(0))
}
之后,你可以使用:
val added = CountMap() + "hello" + "hello" + "world" + "foo" + "bar"
added("hello")
>>2
added("qux")
>>0
您也可添加<条码> 适用条码> 随附物体上的有效载荷,以便你能够直接输入一系列字句,甚至一句:
object CountMap {
def apply(counts: Map[String, Int] = Map[String, Int]()): CountMap = new CountMap(counts.withDefaultValue(0))
def apply(words: Seq[String]): CountMap = CountMap(words.groupBy(w => w).map { case(word, group) => word -> group.length })
def apply(sentence: String): CountMap = CountMap(sentence.split(" "))
}
那么,你会更容易:
CountMap(Seq("hello", "hello", "world", "world", "foo", "bar"))
或:
CountMap("hello hello world world foo bar")