Why is this snippet not printing out: “You successfully implemented the function”
Details:
Why is the type of val actual seeming to be of type List[Either[List[Int], Int]], when I am even saying to the compiler explicitly that actual’s type should be of type List[Int]?
// Flatten a nested list structure
def flatten[T](list: List[Either[List[T], T]]): List[T] = list flatMap {
// TODO: Implement
case list: List[T] => list
case element: T => List(element)
}
implicit def ElementToEitherLeft[T](obj: T) = Left(obj)
implicit def ElementToEitherRight[T](obj: T) = Right(obj)
val list: List[Either[List[Int], Int]] = List(List(1, 1), 2, List(3, 5))
val actual: List[Int] = flatten[Int](list)
val expected = List(1, 1, 2, 3, 5)
if (actual == expected) print("You successfully implemented the function")
else print("Unfortunatly, that's not quite rigth yet")
When you compiled your
flattenyou should have seen a warning like this:If you’d then compiled with with
-unchecked, you’d have seen this:In short,
flatMapisn’t going to unwrap yourEitheritems for you, and what you’ve written only compiles because of some unpleasant facts about type erasure and pattern matching.Fortunately there’s an easy fix:
Or, even better:
Either will work as you expect.