我正在尝试创建一个像这样的通用类:
class A[T](v: Option[T]) {
def this(v: T) = this(Some(v))
def this() = this(None)
def getV = v
}
然后我做了一些测试:
scala> new A getV
res21: Option[Nothing] = None
scala> new A(8) getV
res22: Option[Int] = Some(8)
到现在为止还挺好。但是一旦我尝试调用主构造函数,我就会得到:
scala> new A(Some(8)) getV
<console>:9: error: ambiguous reference to overloaded definition,
both constructor A in class A of type (v: T)A[T]
and constructor A in class A of type (v: Option[T])A[T]
match argument types (Some[Int])
new A(Some(8)) getV
^
scala> new A(None) getV
<console>:9: error: ambiguous reference to overloaded definition,
both constructor A in class A of type (v: T)A[T]
and constructor A in class A of type (v: Option[T])A[T]
match argument types (None.type)
new A(None) getV
^
这两个构造函数之间有什么“模棱两可”的?或者(让我猜猜)这是我对 Scala 的类型系统不了解的另一件事?:)
当然,如果我使用非泛型类,一切都会按预期工作。我的B
课工作得很好:
class B(v: Option[String]) {
def this(v: String) = this(Some(v))
def this() = this(None)
def getV = v
}
scala> new B("ABC") getV
res26: Option[String] = Some(ABC)
scala> new B getV
res27: Option[String] = None
scala> new B(Some("ABC")) getV
res28: Option[String] = Some(ABC)
scala> new B(None) getV
res29: Option[String] = None