首页 文章

Scala在List confusion中重复了参数和参数

提问于
浏览
1

我正在使用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关于"ambiguous reference to overloaded definition, both constructor Queue in class Queue of type (a: T*)Queue[T] and constructor Queue in class Queue of type (heading: List[T], trailing: List[T])Queue[T] match argument types (List[T],List[T])"的投诉 .

那么为什么有必要明确指定类型参数 [T] 否则Scala会将两个单独的列表视为重复参数的整体?我认为它与类型推断有关,有人可以解释一下吗?

2 回答

  • 2

    如果不提供type参数,编译器可以推断 T (对于主构造函数)或 List[T] (对于辅助构造函数) .

  • 2

    Heiko的答案是正确的,但为了澄清这一点, enqueue 中的 T 与您将要创建的 Queue 的上下文中的 T 不同,因此可以推断出导致模糊性的情况 . 为什么你还有2个构造函数?我建议你使用一个伴侣作为外部世界的构造函数:

    class Queue[T] private( private val heading: List[T], private val trailing: List[T]) { /* ... */}
    
    object Queue {
      def apply[T](xs: T*) = new Queue(xs.toList, Nil)
    }
    

相关问题