6

シングルトン型についていくつか質問がありますが、どちらも非常に密接に関連しているため、同じスレッドに投稿しています。

Q1. #1 はコンパイルしないのに #2 はコンパイルするのはなぜですか?

def id(x: Any): x.type = x      // #1
def id(x: AnyRef): x.type = x   // #2

Q2. String私が試した他の参照型の場合は型が正しく推論されますが、そうではありません。どうしてこんなことに?

scala> id("hello")
res3: String = hello

scala> id(BigInt(9))
res4: AnyRef = 9

scala> class Foo
defined class Foo

scala> id(new Foo)
res5: AnyRef = Foo@7c5c5601
4

2 に答える 2

7

シングルトンタイプは、AnyRef子孫のみを参照できます。詳細については、文字列リテラルがScalaシングルトンに準拠する理由を参照してください。

アプリケーションid(BigInt(9))は安定したパスを介して参照できないため、その結果、興味深いシングルトンタイプはありません。

scala> id(new {})
res4: AnyRef = $anon$1@7440d1b0

scala> var o = new {}; id(o)
o: Object = $anon$1@68207d99
res5: AnyRef = $anon$1@68207d99

scala> def o = new {}; id(o)
o: Object
res6: AnyRef = $anon$1@2d76343e

scala> val o = new {}; id(o) // Third time's the charm!
o: Object = $anon$1@3806846c
res7: o.type = $anon$1@3806846c
于 2012-08-19T10:27:27.257 に答える
-1

#2でもエラーが発生します(Scala 2.9.1.finalを使用):

error: illegal dependent method type
  def id(x: AnyRef): x.type = x;          ^
one error found

正しい解決策はid、型パラメーターを使用して make polymorphic を使用することだと思います。

def id[T <: Any](x: T): T = x;
于 2012-08-19T10:14:13.387 に答える