真是個好主意。
它看起來像默認參數衛生問題禁止單身人士類型。
$ scala
Welcome to Scala 2.12.1 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_111).
Type in expressions for evaluation. Or try :help.
scala> private val x = new Object ; def f(foo: x.type = x, i: Int) = i
<console>:11: error: private value x escapes its defining scope as part of type x.type
private val x = new Object ; def f(foo: x.type = x, i: Int) = i
^
scala> val x = new Object ; def f(foo: x.type = (x: x.type), i: Int) = i
x: Object = [email protected]
f: (foo: x.type, i: Int)Int
scala> f(i = 42)
<console>:13: error: type mismatch;
found : Object
required: x.type
f(i = 42)
^
或沒有,這看起來OK:
private[this] val x: Object = new java.lang.Object();
<stable> <accessor> def x: Object = $iw.this.x;
def f(foo: x.type = $iw.this.x, i: Int): Int = i;
<synthetic> def f$default$1: x.type = $iw.this.x
或者是問題的分配爲默認值?
,但你不能做到這一點:
scala> val x: x.type = new Object
<console>:36: error: recursive value x needs type
val x: x.type = new Object
^
我想這個作品,因爲你沒有告訴它x
是x.type
:
scala> object x
defined object x
scala> def f(y: x.type = x, i: Int) = i
f: (y: x.type, i: Int)Int
scala> f(i = 42)
res2: Int = 42
仍然允許明確規定x
,可能會被混淆。
我太害怕調查爲何失敗:
scala> object x$$ ; def f(y: x$$.type = x$$, i: Int) = i
defined object x$$
f: (y: .type, i: Int)Int
scala> f(i = 42)
res0: Int = 42
scala> f(x$$, 42) // or x$$$
<console>:13: error: not found: value x$$
f(x$$, 42)
^
但是,這表明,即使對象是公共的,對它的訪問是通過某種方式名字改編削弱。
你也許可以以某種方式編寫宏。 –