How can I create A Class with Trait On Scala? -
trait genericlinkedlist , case class cons , case object nil created below. question want use genericlinkedlist know when write code var list = new genericlinkedlist
, not cause traits cannot create object , right? want create class extends genericlinkedlist cannot. how can fix ?
trait genericlinkedlist [+t] { def prepend[tt >: t](x: tt): genericlinkedlist[tt] = 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 unable of doing
val list = new genericlinkedlist
is goal creating empty list?
you can do
val list = new genericlinkedlist[int] { }
since trait not abstract, it's not pretty. can alternatively define companion object trait
object genericlinkedlist { def apply[t](): genericlinkedlist[t] = nil }
and use initialize empty list way
scala> val x = genericlinkedlist[int]() // x: genericlinkedlist[int] = nil scala> x.prepend(42) // res0: genericlinkedlist[int] = cons(42,nil)
by way, universal match
in prepend
implementation useless. can do
def prepend[tt >: t](x: tt): genericlinkedlist[tt] = cons(x, this)
Comments
Post a Comment