Scala类似于“with object do begin ... end”(快捷方法访问)

时间:2013-03-16 14:03:14

标签: scala

在旧生锈的Pascal中,有一个方便的构造来对对象或记录执行一系列操作:

with obj do
begin
  methodCall
  otherMethodCall
  ...
end

我正试图在scala中触摸类似的东西,但我头脑中遗漏了一些东西:)

是否有可能以某种方式实现这样的效果,就好像obj处于传递闭包的当前范围并且表现如下:

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

但是在自定义语法中:

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

直觉上我觉得它比noyes但好奇心想知道。

2 个答案:

答案 0 :(得分:12)

你的意思是这样吗?

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

// later as long as file is in scope

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

您可以使用import关键字将对象的方法放在范围内。

答案 1 :(得分:11)

一种可能性是tap方法:

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

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

或使用浓缩后

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

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

我认为使用宏你甚至可以获得所需的语法(并避免创建函数对象的开销),但我会将其留给其他人。