Type mismatch when using map on a zipped list in Scala

Consider this code :

  /** Takes a list and turns it into an infinite looping stream. */
  def loop(l: List[Char]): LazyList[Char] = {
      l.to(LazyList)  #:::loop(l)
  }

  /** Encodes a sequence of characters with a looped key. */
  def codec(message: Seq[Char], key: Seq[Char], cipher: (Char, Char) => Char): Seq[Char] = {
    val loopedKey = loop(key.toList)
    val mergedMessage = message.toList zip loopedKey
    val xorResult = mergedMessage.map(cipher)
    xorResult.toSeq
  }

The loop function is correct, but the function named codec yield the following error when compiled :

[error]  type mismatch;
[error]  found   : (Char, Char) => Char
[error]  required: ((Char, Char)) => ?
[error]     val xorResult = mergedMessage.map(cipher)

I don’t understand why the required part says : ((Char, Char)) => ?.

>Solution :

(Char, Char) => Char is a function accepting 2 Chars and returning Char while zip will result in a collection of tuples (Char, Char). One option is to change cipher type to accept a tuple – ((Char, Char)) => Char:

def codec(message: Seq[Char], key: Seq[Char], cipher: ((Char, Char)) => Char): Seq[Char] = ...

Without changing the signature – access tuple elements directly:

val xorResult = mergedMessage.map(t => cipher(t._1, t._2))

Or just use tupled:

val xorResult = mergedMessage.map(cipher.tupled)

Leave a Reply