【问题标题】:Scala repeated parameters and parameters in List confusionScala重复参数和List混淆中的参数
【发布时间】: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


    【解决方案1】:

    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)
    }
    

    【讨论】:

    • 谢谢 drexin。我不太明白您的观点,即 enqueue 中的 T 与您即将创建的 Queue 上下文中的 T 不同 我认为 enqueue 中的 T 与 in 中的 T 相同class Queue[T],这就是为什么 a::trailing 没有给出错误。而且我最好将 Queue 设置为 Trait,并将对象用作外部世界的工厂。谢谢你的建议。
    • new Queue 中的T 没有指定,所以编译器会尝试推断它。由于您有两个与您的 List[T], List[T] 构造函数匹配的构造函数,因此编译器无法推断出您要调用的构造函数。当您从当前上下文显式传入T 时,编译器知道,新实例的T 应该是您的旧T 而不是List[T]
    • 我现在明白了。非常感谢。
    【解决方案2】:

    如果您不提供类型参数,编译器可能会推断出T(用于主构造函数)或List[T](用于辅助构造函数)。

    【讨论】:

    • 谢谢海科。显然我没有意识到辅助构造函数可以应用于 2 List[U] with T=List[U].
    猜你喜欢
    • 2018-10-22
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 2017-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-23
    相关资源
    最近更新 更多