开发者

Scala: For Comprehension compile error (newbie question)

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

  case cl开发者_StackOverflow社区ass 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


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)
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜