首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >类中具有协变量类型参数和私有构造函数的

类中具有协变量类型参数和私有构造函数的
EN

Stack Overflow用户
提问于 2015-09-26 10:57:10
回答 1查看 248关注 0票数 1

下面是楼梯书中的一个例子:

代码语言:javascript
运行
复制
object Example {
  class Queue[+T] private (
                          private[this] var leading: List[T],
                          private [this] var trailing: List[T]
                            ) {
    private def mirror: Unit = {
      if(leading.isEmpty) {
        while(!trailing.isEmpty) {
          leading = trailing.head :: leading
          trailing = trailing.tail
        }
      }
    }

    // cannot resolve symbol U
    def this[U >: T](xs: U*) = this(xs.toList, Nil)
    // Covariant type T occurs in contra-variant position
    def this(xs: T*) = this(xs.toList, Nil)

    def head: T = {
      mirror
      leading.head
    }

    def tail: Queue[T] = {
      mirror
      new Queue(leading.tail, trailing)
    }

    def enqueue[U >: T](x: U) = new Queue[U](leading, x :: trailing)

    def size = leading.size + trailing.size
  }   
}

我增加了以下几行:

代码语言:javascript
运行
复制
    // cannot resolve symbol U
    def this[U >: T](xs: U*) = this(xs.toList, Nil)
    // Covariant type T occurs in contra-variant position
    def this(xs: T*) = this(xs.toList, Nil)

因为我需要一些公共构造函数来创建新的队列。但是每个构造函数都有自己的问题(见注释)。怎样才能解决这些问题呢?

更新

没有参数的构造函数似乎编译得很好:

代码语言:javascript
运行
复制
def this() = this(Nil, Nil)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-09-26 11:18:01

在Scala中,与多个构造器相比,首选的替代方法是有一个具有apply方法的配套对象:

代码语言:javascript
运行
复制
object Queue {
  def apply[T, U <: T](xs: U*): Queue[T] = new Queue(xs.toList, Nil)
  def apply[T](xs: T*): Queue[T] = new Queue(xs.toList, Nil)
}

这样,您可以使用val q = Queue(1, 2, 3)实例化队列(注意缺少new),就像对Scala标准集合中的大多数数据结构一样。

我上面写的对象不会编译,因为两个apply方法在擦除后具有相同的类型,有不同的方法来解决这个问题,但是在这个精确的例子中,我认为最好只是简单地使用第二个函数。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32796409

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档