Scala analogue to "with the do begin ... end object" (access to the quick access method)

In old rusty Pascal, there was a convenient design for performing a sequence of actions on an object or record:

with obj do
begin
  methodCall
  otherMethodCall
  ...
end

I am trying to touch something similar in scala, but something is missing in my head :)

Is it possible in some way to achieve such an effect as if obj was in the current area of ​​the passed closure and behaved like this:

{
  import obj._
  callObjMethod(x, y)
  objVal.doSomething()
  ...
}

But in custom syntax, for example:

doWith (obj) {
  callObjMethod(x, y)
  objVal.doSomething()
}

Intuitively, I feel it is more nothan yesthat, but curiosity wants to know for sure.

+5
source share
2 answers

One possibility is the method tap:

def tap[A](obj: A)(actions: (A => _)*) = {
  actions.foreach { _(obj) }
  obj
}

tap(obj) (
  _.callObjMethod(x, y),
  _.objVal.doSomething()
)

or after using enrichment

implicit class RichAny[A](val obj: A) extends AnyVal {
  def tap(actions: (A => _)*) = {
    actions.foreach { _(obj) }
    obj
  }
}

obj.tap (
  _.callObjMethod(x, y),
  _.objVal.doSomething()
)

, ( ), - .

+11

?

val file = new java.io.File(".")

// later as long as file is in scope

{
  import file._
  println(isDirectory)
  println(getCanonicalPath())
}  

import, .

+12

All Articles