Scala“类似句子”的函数定义

时间:2015-06-11 19:10:54

标签: function scala styles

我正在重构一些代码,并想学习如何编写Scala方法,以便它们可以像:

foo = Map("Hello" -> 1)
foo contains "Hello"

其中“contains”是我想要模仿的样式。这是我重构的代码(来自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有类似的东西)中调用它的内容会非常有用,因为我已经做了很多搜索而无法找到我想要描述的内容。 / p>

1 个答案:

答案 0 :(得分:2)

这被称为Infix Notation,只要你有一个参数函数,它就不需要任何特殊的东西。

它不适合您的原因是您需要调用其方法的对象。以下编译:

class Bob {
  def hey(statement:String): String = statement match {
    case x if this isSilent x  => "Fine. Be that way!"
    case x if this shouting x  => "Whoa, chill out!"
    case x if this 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("?")

}