Reputation: 483
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.
Upvotes: 0
Views: 208
Reputation: 332
Actually there is some problems with your code:
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)
Upvotes: 2