0
votes

Below is the map1.scala file in IntelijIDEA

It seems i hit the wall once again. I have no idea why the following is error:

abstract class List[T] {
   def map[U](f: T => U): List[U] = {
     this match {
       case Nil => this
       case x :: xs => ???
     }
   }
 }

case Nil: pattern type is incompatible with expected type: found Nil.type expected List[T] this: expression of type List[T] doesn't conform to expected type List[U] x :: xs Pattern type incompatible found ::B required List[T]..

I tried everything... But still have this problem. However knows please respond.

1
Nil is a type of List from standard library and you compare it with your own class List. Rename your list to MyList, MyNil and do not confuse yourself.Nikita

1 Answers

2
votes

Actually there is some problems with your code:

  • invariant type parameter T of List
  • non-existent object Nil
  • absent operator ::
  • absent object :: with unapply function

Try this:

abstract class List[+A]
  def head: A
  def tail: List[A]

  def map[B](f: A => B): List[B] = 
    if (this == Nil) Nil 
    else new ::(f(head), tail map f)
}

case object Nil extends List[Nothing] {
  def head = ??? // not interested in throwing more appropriate exception
  def tail = ???
} 

case class ::[T](head: T, tail: List[T]) extends List[T]

Then you can use it

(1 :: 2 :: 3 :: Nil).map(_.toString)