简体   繁体   English

在Scala中实例化类型参数类的最佳方法

[英]Best way to instantiate a type parameter class in Scala

I wanted to have a Queue class that could be used the same way as a list. 我想要一个可以与列表相同使用的Queue类。

For instance, 例如,

val q = Queue()

would instantiate an empty queue. 将实例化一个空队列。

For that purpose I tried using a companion class : 为此,我尝试使用一个伴随类:

object Queue {
    def apply() = new Queue[Any]
}

Is that the right way to do it ? 那是正确的方法吗?

Using the apply method of the companion object is the right way to do it, but you could also add a type parameter on apply itself: 使用伴随对象的apply方法是正确的方法,但是您也可以在apply自身上添加类型参数:

object Queue {
    def apply[T]() = new Queue[T]
}

So that you can create a Queue of the right type: 这样您就可以创建正确类型的Queue

val q = Queue[Int]()

Usually you also allow populating the sequence on creation, so that the element type can be inferred, as in: 通常,您还允许在创建时填充序列,以便可以推断元素类型,如下所示:

def apply[T](elms: T*) = ???

So that you can do: 这样您就可以:

val q = Queue(1,2,3) // q is a Queue[Int]

Yes. 是。

If you want to initialise an object without using new , then using apply() as a factory method in the companion is absolutely the right way to go about it. 如果要初始化对象而不使用new ,则在伴侣中使用apply()作为工厂方法绝对是正确的方法。

You might also want to consider a more specific factory (or factories) to help make your code more self-documenting. 您可能还需要考虑一个或更具体的工厂(或多个工厂),以帮助使您的代码更具自记录性。

object Queue {
  def apply[T](xs: T*) = new Queue(xs: _*)
  def empty[T] = new Queue[T]()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM