在流,选项和创建元组上进行模式匹配 [英] Pattern matching on Stream, Option and creating a Tuple
问题描述
我有一张桌子table1
:
id: Int
externalId: Int
value: String
对于给定的externalId
value
可以是NULL
,或者可能根本不存在.我想根据这种情况返回一个元组:
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:
- 如果不存在,则返回
("notExists", Nil)
- 如果存在但
NULL
,则返回("existsButNull", Nil)
- 如果存在但不存在
NULL
,则返回("existsWithValue", ???)
- If it doesn't exist then return
("notExists", Nil)
- If it exists but
NULL
then return("existsButNull", Nil)
- If it exists and not
NULL
then return("existsWithValue", ???)
其中,???
应该是具有给定externalId
的所有记录的value
列表.我尝试这样做:
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)
}
请注意,如果值存在且不为NULL
,并且记录多于1条记录,则value
不能为NULL
.例如,这种情况不可能
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"
这与Stream
+ Option
的模式匹配有关,但是我不知道该怎么做.
It has to do with pattern matching of Stream
+ Option
but I can't figure out how to do this.
推荐答案
在流上进行模式匹配可能不是一个好主意,我假设要返回的元素数量足够小以适合内存吗?仅在元素可能不适合内存的情况下才使用流,否则将流转换为列表然后再使用列表会更容易:
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))
}
这篇关于在流,选项和创建元组上进行模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!