4

I am getting a type mismatch compile error for the following code:

  case class MyClass(name: String)
  def getMyClass(id : String) = {
      //For now ignore the id field
      Some(Seq(MyClass("test1"), MyClass("test2"), MyClass("test3"), MyClass("test4"), MyClass("test5")))
  }

  def getHeader() = {
    Map(
      "n" -> List(Map("s"->"t"), Map("s"->"t"), Map("s"->"t")),
      "o" -> List(Map("s"->"t"), Map("s"->"t"), Map("s"->"t")),
      "id" -> "12345"
    )
  }
  def castToString(any: Option[Any]): Option[String] = {
    any match {
      case Some(value: String) => Some(value)
      case _ => None
    }
  }

  val h = getHeader()

  for{
    id <- castToString(h.get("id")) //I hate I have to do this but the map is a Map[String,Any]
    m <- getMyClass(id)  //This strips the Some from the Some(Seq[MyClass])
    item <- m     //XXXXXXXX Compile errors
    oList <- h.get("o")
    nList <- h.get("n")

  } yield {
    (oList, nList, item)
  }

The error is:

C:\temp\s.scala:28: error: type mismatch;
 found   : Seq[(java.lang.Object, java.lang.Object, this.MyClass)]
 required: Option[?]
        item <- m
             ^

But m is of type Seq[MyClass]. I am trying to iterate through the list and set item

Tihom
  • 3,384
  • 6
  • 36
  • 47
  • 2
    Compare with this simplified example of the issue: `for {a <- Some(List(1,2)); b <- List(1,2)} yield (a,b)`. A good explanation/answer should discuss how `for...yield` is de-sugared into the basic `map/flatMap/filter` method calls. Some [details here](http://www.lambdascale.com/tag/for-comprehension/). –  Jun 23 '11 at 19:49

2 Answers2

4

You can't mix container types in this way, specifically given the signature of Option.flatMap (to which this expression is desugared - see the comment by pst). However, there's a pretty easy solution:

for{
  id <- castToString(h.get("id")).toSeq
  m <- getMyClass(id).toSeq
  oList <- h.get("o")
  nList <- h.get("n")
} yield {
  (oList, nList, item)
}
Kris Nuttycombe
  • 4,560
  • 1
  • 26
  • 29
0

A better explanation of why the code you mentioned doesnt work can be found here: What is Scala's yield?

You could change your code to the one Kris posted.

Community
  • 1
  • 1
Udayakumar Rayala
  • 2,264
  • 1
  • 20
  • 17