2013-04-01 72 views
0

我想在使用anorm從play2模塊查詢mysql數據庫時使用模式匹配。代碼如下所示:播放2 Anorm和scala模式匹配

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) 

} 

但名稱:字符串不匹配任何東西(已經嘗試只匹配整數,它工作正常)。在我的db上,實體表「名稱」列的類型是varchar(45)。

我失蹤了嗎?

+0

與嘗試的名字:選項[字符串]',因爲該列可爲空。 – maba

+0

與選項[字符串]相同的錯誤或者甚至某些[字符串] – jdrm

+0

您提到了錯誤。那是什麼錯誤? – maba

回答

0

您可以嘗試在Int上匹配和指定的通配符。

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


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

是的,我可以做到這一點...但是不是類型模式匹配的想法能夠避免投射模式匹配的結果嗎? – jdrm

0

如果名稱爲空那麼這個匹配應該工作:

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