Pattern matching on Stream, Option and creating a Tuple

给你一囗甜甜゛ 提交于 2019-12-24 22:28:34

问题


I have a table table1:

id: Int
externalId: Int
value: String

For a given externalId value can be NULL or it might not exist at all. I want to return a tuple depending on this condition:

  1. If it doesn't exist then return ("notExists", Nil)
  2. If it exists but NULL then return ("existsButNull", Nil)
  3. If it exists and not NULL then return ("existsWithValue", ???)

where ??? should be a list of value for all records with the given externalId. I tried to do this:

DB.withConnection { implicit c =>
  SQL("SELECT value from table1 WHERE externalId = 333")
    .map { case Row(value: Option[String]) => value }
} match {
  case Some(x) #:: xs =>
    //????????????
    ("existsWithValue", ???)
  case None #::xs => ("existsButNull", Nil)
  case Stream.empty => ("notExists", Nil)
}

Note that if value exists and is not NULL and if there are more than 1 record of it then value can't be NULL. For example, this situation is NOT possible

1 123 "Value1"
2 123 "Value2"
3 123  NULL    -- NOT possible  
4 123 "Value4"

It has to do with pattern matching of Stream + Option but I can't figure out how to do this.


回答1:


Pattern matching on a stream is probably not a good idea, I'm assuming the number of elements being returned is small enough to fit into memory? You would only work with a stream if it's likely that the elements won't fit in memory, otherwise it's much easier to convert the stream to a list, and then work with the list:

DB.withConnection { implicit c =>
  SQL("SELECT value from table1 WHERE externalId = 333")
    .map { case Row(value: Option[String]) => value }
    .toList
} match {
  case Nil => ("notExists", Nil)
  case List(None) => ("existsButNull", Nil)
  case xs => ("existsWithValue", xs.flatMap(_.toList))
}


来源:https://stackoverflow.com/questions/20768272/pattern-matching-on-stream-option-and-creating-a-tuple

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!