简体   繁体   English

如何在Scala上使用Trait创建类?

[英]How can I create A Class with Trait On Scala?

Trait GenericLinkedList , case class Cons and case object Nil were created like below. 如下创建Trait GenericLinkedList,案例类Cons和案例对象Nil。 The question is I want to use this genericLinkedList however as you know when we write this code var list = new GenericLinkedList , it will not cause Traits cannot create any object , Right? 问题是我想使用此genericLinkedList,但是正如您所知,当我们编写此代码时var list = new GenericLinkedList ,这不会导致Traits无法创建任何对象,对吗? I want to create a class which extends GenericLinkedList but I cannot. 我想创建一个扩展GenericLinkedList的类,但不能。 How can I fix it ? 我该如何解决?

trait GenericLinkedList [+T] {
def prepend[TT >: T](x: TT): GenericLinkedList[TT] = this match {
    case _ => Cons(x,this) 
  }
}
case class Cons[+T](head: T,tail: GenericLinkedList[T]) extends GenericLinkedList[T]
case object Nil extends GenericLinkedList[Nothing]

Your issue seems to be unable of doing 您的问题似乎无法解决

val list = new GenericLinkedList

Is your goal creating an empty list? 您的目标是创建一个空列表吗?

You can do 你可以做

val list = new GenericLinkedList[Int] { }

since the trait is not abstract, but it's not pretty. 因为特征不是抽象的,但不是很漂亮。 You can alternatively define a companion object for your trait 您也可以为自己的特征定义伴侣对象

object GenericLinkedList {
  def apply[T](): GenericLinkedList[T] = Nil
}

and use it to initialize an empty list this way 然后用它来初始化一个空列表

scala> val x = GenericLinkedList[Int]()
// x: GenericLinkedList[Int] = Nil

scala> x.prepend(42)
// res0: GenericLinkedList[Int] = Cons(42,Nil)

By the way, the universal match in the prepend implementation is useless. 顺便说一句, prepend实现中的通用match是没有用的。 You can just do 你可以做

 def prepend[TT >: T](x: TT): GenericLinkedList[TT] = Cons(x, this)

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

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