Vil*_*tas 4 generics scala multiple-constructors scala-2.9
我正在尝试创建这样的泛型类:
class A[T](v: Option[T]) {
def this(v: T) = this(Some(v))
def this() = this(None)
def getV = v
}
Run Code Online (Sandbox Code Playgroud)
然后我做了一些测试:
scala> new A getV
res21: Option[Nothing] = None
scala> new A(8) getV
res22: Option[Int] = Some(8)
Run Code Online (Sandbox Code Playgroud)
到现在为止还挺好.但是当我尝试调用主构造函数时,我得到了这个:
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
^
Run Code Online (Sandbox Code Playgroud)
这两个构造函数之间有什么"模糊"?或者(让我猜)这是我不了解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
Run Code Online (Sandbox Code Playgroud)
该new A(Some(8))可以是:
A[Int]via主构造函数的新实例,A[Option[Int]]via alternate构造函数的新实例.您可以明确指定类型,例如new A[Int](Some(8)).