Search code examples
scalacompiler-errors

Scala "for comprehension" compilation error


I don't think I fully understand the inner workings of the "for comprehension" mechanism. In the code below, the first two "for comprehension" compile but the third, which is the combination of the first two, does not.

How to change the code to compile and work? Thanks

object Test {
 val lst: List[Int] = List(1,2,3,4)
 val optList: Option[List[Int]] = Option(lst)

 for {
   num: Int <- lst
 } yield num

 for {
   qn: List[Int] <- optList
 } yield qn

 for {                        // Error: Type mismatch. Required: Option[B_], found: List[Int]
   qn: List[Int] <- optList
   num: Int <- qn
 } yield num
}


Solution

  • Your code compiles and works with Scala 3. For Scala 2, add the explicit conversion (what Scala 3 does implicitly):

     for {
       qn: List[Int] <- Option.option2Iterable(optList)
       num: Int <- qn
     } yield num
    

    The answer is similar to the comment of Luis Miguel Mejía Suárez: "just convert the Option into a List".