looking for some solutions? You are welcome.

SOLVED: covariant type T in linked list

Vadim:

I want to create a singly-linked list with add methods according the tutorial

Learning Scala by building Scala - Lists

Can you please resolve error?

Error:(6, 13) covariant type T occurs in contravariant position in type T of value element def add(element: T): MyLinkedList[T]

The error appeared when I add + to generic [T], because method apply didn't work without +.

sealed trait MyLinkedList[+T] {
    def add(element: T): MyLinkedList[T]
}

object MyLinkedList {
  def apply[T](elements: T*): MyLinkedList[T] = {
    if (elements.isEmpty) {
      new Empty[Nothing]
    } else {
      Cons(elements.head, apply(elements.tail: _*))
    }
  }

  final case class Cons[T](element: T, rest: MyLinkedList[T]) extends MyLinkedList[T] {
        override def add(element: T): MyLinkedList[T] = ???
  }

  final case class Empty[T]() extends MyLinkedList[T] {
        override def add(element: T): MyLinkedList[T] = ???
  }
}



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
Share:

No comments:

Recent