Scala "Sentence-Like" 函数定义

Scala "Sentence-Like" Function Definition

我正在重构一些代码,想了解 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、shouting 和 asking 函数都可以用那种风格编写,这样我就可以写:

case x if isSilent x => ...

感谢您的帮助!此外,知道这在 Scala(以及其他函数式语言,因为我认为 Haskell 有类似的东西)中被称为什么会非常有帮助,因为我已经做了很多搜索但找不到我正在尝试的东西描述。

这被称为 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("?")

}