Scala在同一个对象上执行多个操作而不重复它的名字

在kotlin中,有一个可以用来实现以下function的接收器function:

 fun alphabet() = with(StringBuilder()) { for (letter in 'A'..'Z') { append(letter) } append("\nNow I know the alphabet!") toString() } 

所以你不必重复StringBuilder对象。 我想知道在Scala中做什么的语法?

它或多或少是相同的(就我所知,从您的示例中)作为Scala中的一个输入。

 def alphabet = { val builder = new StringBuilder import builder._ for(letter <- 'A' to 'Z') append(letter) append("\nNow I know the alphabet!") mkString // toString would be ambiguous unfortunately } 

或者你可以用两种扩展方法去寻找更实用的方法。 我们称他们为tappipe

 implicit class TapExtensions[A](private val a: A) extends AnyVal { def tap[B](f: A => B): A = { f(a); a } def pipe[B](f: A => B): B = f(a) } def alphabet = new StringBuilder() .tap( b => for(letter <- 'A' to 'Z') b.append(letter) ) .tap( _.append("\nNow I know the alphabet!") ) .pipe( _.toString ) 

典型的function.foldLeft是你需要在scala中

 ('A' to 'Z') .foldLeft(new StringBuilder)((a, b) => a append b) .append("\nNow I know the alphabet!") 

+而不是append

 ('A' to 'Z') .foldLeft(new StringBuilder)((a, b) => a + b) + "\nNow I know the alphabet!" 

产量

 ABCDEFGHIJKLMNOPQRSTUVWXYZ Now I know the alphabet! 

对于具体的任务,你也可以使用mkString函数来获得你想要的结果这是你可以做的

 ('A' to 'Z').mkString("") + "\nNow I know the alphabet!" 

输出:

 ABCDEFGHIJKLMNOPQRSTUVWXYZ Now I know the alphabet! 

希望这可以帮助!