使用Scala中的函数映射实例

Bor*_*ijk 2 scala function

假设我有一个本地方法/功能

def withExclamation(string: String) = string + "!"
Run Code Online (Sandbox Code Playgroud)

Scala中是否有通过提供此方法来转换实例的方法?假设我想在字符串中附加感叹号.就像是:

val greeting = "Hello"
val loudGreeting = greeting.applyFunction(withExclamation) //result: "Hello!"
Run Code Online (Sandbox Code Playgroud)

我希望能够在实例上编写链转换时调用(本地)函数.

编辑:多个答案显示如何编程这种可能性,所以似乎这个功能不存在于任意类.对我来说,这个功能似乎非常强大.考虑在Java中我想在String上执行许多操作:

appendExclamationMark(" Hello! ".trim().toUpperCase()); //"HELLO!"
Run Code Online (Sandbox Code Playgroud)

操作顺序与他们阅读的方式不同.最后一个操作appendExclamationMark是出现的第一个单词.目前在Java中我有时会做:

Function.<String>identity()
    .andThen(String::trim)
    .andThen(String::toUpperCase)
    .andThen(this::appendExclamationMark)
    .apply(" Hello "); //"HELLO!"
Run Code Online (Sandbox Code Playgroud)

哪个在表示实例上的操作链方面读得更好,但是也包含很多噪声,并且在最后一行使用String实例并不直观.我想写:

" Hello "
    .applyFunction(String::trim)
    .applyFunction(String::toUpperCase)
    .applyFunction(this::withExclamation); //"HELLO!"
Run Code Online (Sandbox Code Playgroud)

显然,applyFunction函数的名称可以是任何东西(请更短).我认为向后兼容是Java Object没有这个的唯一原因.有没有任何技术原因可以解释为什么没有添加Any或AnyRef类?

Yuv*_*kov 5

您可以使用隐式类来执行此操作,该类提供了使用您自己的方法扩展现有类型的方法:

object StringOps {
  implicit class RichString(val s: String) extends AnyVal {
    def withExclamation: String = s"$s!" 
  }

  def main(args: Array[String]): Unit = {
    val m = "hello"
    println(m.withExclamation)
  }
}
Run Code Online (Sandbox Code Playgroud)

产量:

hello!
Run Code Online (Sandbox Code Playgroud)