ttt ttt - 8 days ago 4
Scala Question

Scala performs multiple operations on the same object without repeating its name

In kotlin, there is a

receiver function you can use to achieve following:

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

So you don't have to repeat the
object. I am wondering what's the syntax of doing it in Scala?


It's more or less the same (as far as I can see from your example) as an import in 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

Or you could go for a more functional looking approach with two extension methods. Let's call them tap and pipe.

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 )