【发布时间】:2015-08-27 15:50:08
【问题描述】:
我正在重构一些代码,并想了解如何编写 Scala 方法,以便可以将它们编写为:
foo = Map("Hello" -> 1)
foo contains "Hello"
“包含”是我想要效仿的风格。这是我正在重构的代码(来自 exercism.io):
class Bob {
def hey(statement:String): String = statement match {
case x if isSilent(x) => "Fine. Be that way!"
case x if shouting(x) => "Whoa, chill out!"
case x if asking(x) => "Sure."
case _ => "Whatever."
}
def isSilent2:String => Boolean = _.trim.isEmpty
def isSilent (str:String) = str.trim.isEmpty
def shouting(str:String): Boolean = str.toUpperCase == str && str.toLowerCase != str
def asking(str:String): Boolean = str.endsWith("?")
}
理想情况下,我想让我的 isSilent、喊叫和询问函数都能够以这种风格编写,以便我可以编写:
case x if isSilent x => ...
感谢您的帮助!此外,知道这在 Scala(和其他函数式语言,因为我认为 Haskell 有类似的东西)中被称为什么会非常有帮助,因为我已经做了很多搜索并且找不到我想要描述的内容。
【问题讨论】: