【发布时间】:2012-05-29 15:40:42
【问题描述】:
我使用的是 Scala 2.9
我有一堂课:
class Queue[T] private( private val heading: List[T], private val trailing: List[T] ) {
def this( a: T* ) = this( a.toList, Nil )
private def mirror = {
if ( heading.isEmpty ) {
new Queue[T]( trailing.reverse, Nil )
} else this
}
def head = {
val q = mirror
if ( q.heading.isEmpty ) None else new Some(q.heading.head)
}
def tail = {
val q = mirror
if ( q.heading.isEmpty ) q else new Queue[T]( q.heading.tail, trailing )
}
def enqueue( a: T ) = {
new Queue[T]( heading, a::trailing )
}
}
在方法入队中,如果我写new Queue( heading, a::trailing )(省略类型参数[T]),代码将无法编译并且scalac抱怨“对重载定义的模糊引用,类型为Queue的类中的构造函数Queue( a: T*)Queue[T] 和类Queue 中的构造函数Queue 类型(标题:List[T],尾随:List[T])Queue[T] 匹配参数类型(List[T],List[T]) ”。
那么为什么需要显式指定类型参数[T] 否则Scala 会将两个单独的List 视为一个整体来处理重复参数?我认为它与类型推断有关,有人可以解释一下吗?
【问题讨论】:
标签: scala