Search code examples
scalafor-comprehension

Scala for-comprehension type inference


The next code

  def f(chars: List[Char]): List[List[Char]] = chars match {
    case Nil => List(Nil)
    case x :: xs => for {
      v <- f(xs)
    } yield List(x) :: v
  }

gives the error message

- type mismatch;  found   : List[List[Any]]  required: List[List[Char]]

Please help me understand why 'for' chooses the most general Any instead of Char here? What topic in language spec should I read? Thanks.


Solution

  • The result, you are yielding is a mix of List[List[List[Char]]] and List[List[Char]]. Scala upcasts that to List[List[Any]]. For your case either of the following will do the job:

    scala>  def f(chars: List[Char]): List[List[Char]] = chars match {
         |     case Nil => List(Nil)
         |     case x :: xs => for {
         |       v <- f(xs)
         |     } yield x :: v
         |   }
    f: (chars: List[Char])List[List[Char]]
    
    scala>  def f(chars: List[Char]): List[List[Char]] = chars match {
         |     case Nil => List(Nil)
         |     case x :: xs => for {
         |       v <- f(xs)
         |     } yield List(x) ++ v
         |   }
    f: (chars: List[Char])List[List[Char]]