"用“;在Scala中从JavaScript构建

"with" construct from JavaScript in Scala

本文关键字:中从 JavaScript Scala 构建 quot      更新时间:2023-09-26

Scala是否有类似于JavaScript的with的东西,或者它是否可以以某种方式实现(例如库、implicits或宏(?

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 _
                 ^