Search code examples
scalatypes

Suffering from Nothing


How does the A turn to be Nothing in the process?

def seq2map[A](src: Seq[A]): Map[A, A] = {
    def pair = for {
        f <- src.headOption
        s <- src.headOption
    } yield (f, s)
    Stream continually pair takeWhile(_ isDefined) toMap
}

error: Expression of type Map[Nothing, Nothing] doesn't conform to expected type Map[A, A]


Solution

  • I get

    <console>:12: error: Cannot prove that Option[(A, A)] <:< (T, U).
               Stream continually pair takeWhile(_ isDefined) toMap
                                                              ^
    

    because

    scala> val src = (1 to 10).toSeq
    src: scala.collection.immutable.Range = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    
    scala>     def pair = for {
         |         f <- src.headOption
         |         s <- src.headOption
         |     } yield (f, s)
    pair: Option[(Int, Int)]
    

    is not a pair, but an Option.

    scala> (Stream continually pair takeWhile (_.isDefined)).flatten
    res0: scala.collection.immutable.Stream[(Int, Int)] = Stream((1,1), ?)
    

    is a stream of pairs.

    Just waiting for the game to start.