简体   繁体   English

播放2个Anorm和Scala模式匹配

[英]Play 2 Anorm and scala pattern matching

I am trying to use pattern matching when querying a mysql database from a play2 module using anorm. 我在使用anorm从play2模块查询mysql数据库时尝试使用模式匹配。 Code looks like this: 代码如下:

def test= Action {
    DB.withConnection { implicit c =>
    val entities = SQL("SELECT entity.idEntity, entity.name FROM entity")().collect {
        case Row(id:Int, name:String) => Entity(id, name)
  }
  printList(entities.toList)

}

But the name:String is not matching anything (already tried to match just the integer and it works fine). 但是name:String不匹配任何内容(已经尝试匹配整数并且可以正常工作)。 On my db the entity table "name" column type is varchar(45). 在我的数据库中,实体表的“名称”列类型为varchar(45)。

Anything I am missing? 我有什么想念的吗?

You can try to match Row on an Int and a named wild card. 您可以尝试将Int上的Row与命名的通配符匹配。

scala> new Row(0,"foo")
res0: Row = Row(0,foo)


scala> res0 match{
     | case Row(i: Int,s @ _) => println(i + " " + s)
     | }
0 foo

如果名称可为空,则此匹配应起作用:

case Row(id:Int, Some(name:String)) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM