Scala 是否有类似于 JavaScript 的 with
的东西,或者可以通过某种方式实现(例如库、隐式或宏)吗?
JS 中 with
的示例:
function p(){
document.write("I am " + this.constructor.name + ".<br>");
}
function o1(){
this.p = p;
}
var i1 = new o1();
i1.p();
p();
with(i1){ p(); }
输出:
I am o1.
I am Window.
I am o1.
我正在寻找的示例:
class A { def x { ... } }
val a = new A
with(a){ x }
<小时/>
我唯一想到的是使用匿名函数,但这只是名称替换,仅此而已(而且非常冗长)。
( (aa:A) => aa.x )(a)
最佳答案
import a._
// code below can now use a's methods without referencing it
如果要限制导入范围,请使用大括号:
{
import a._
// namespace madness
}
// everything's back to normal here
来自 REPL 的示例:
scala> val i = ""
i: java.lang.String = ""
scala> import i._
import i._
scala> length
res0: Int = 0
<小时/>
您还可以执行有限导入:
import a.{thingImGonnaUse, anotherImportantThing}
甚至重命名它们:
import a.{thingImGonnaUse => tigu, anotherImportantThing => ait}
这比仅仅执行 val ait = a.anotherImportantThing _
更强大,因为它仍然允许您使用重载版本:
scala> val i = "0123456"
i: java.lang.String = 0123456
scala> import i.{substring => x}
import i.{substring=>x}
scala> x(3)
res1: java.lang.String = 3456
scala> x(2,3)
res2: java.lang.String = 2
scala> val y = i.substring _
<console>:15: error: ambiguous reference to overloaded definition,
both method substring in class String of type (x$1: Int, x$2: Int)java.lang.String
and method substring in class String of type (x$1: Int)java.lang.String
match expected type ?
val y = i.substring _
^
关于javascript - "with"从 Scala 中的 JavaScript 构造,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25134876/