我将尝试创建一个类似这样的通用类:
到目前为止,一切都很顺利。但是当我尝试调用主构造函数时,会出现以下错误:
这两个构造函数之间有什么“不明确”的地方?或者(让我猜一下)这又是我不了解Scala类型系统的另一件事情?
当然,如果我使用非泛型类,一切都按预期工作。我的B类完全正常:
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