在游戏中使用 Scala 和 anorm 将结果集转换为 Seq[(String,String)]

Convert result set to Seq[(String,String)] using Scala and anorm in play

我尝试使用异常从 mySQL 数据库 table 获取结果集。这是我的代码。

package models
import play.api.db._
import play.api.Play.current
import scala.collection.mutable._
import anorm._
import anorm.SqlParser._

    case class Brand(id: Int, name: String)


        object Brand {

             /**
            * Parse a Brand from a ResultSet
            */
            val simple = {
                get[Int]("m_brand.idbrand") ~
                get[String]("m_brand.brandName") map {
                case id~name => Brand(id, name)
                }
            }

            /**
            * Construct the Map[String,String] needed to fill a select options set.
            */
            def options: Seq[(String,String)] = DB.withConnection { implicit connection =>
                 SQL("select * from m_brand order by brandName").as(Brand.simple *).
                    foldLeft[Seq[(String, String)]](Nil) { (cs, c) => 
                     c.id.fold(cs) { id => cs :+ (id.toString -> c.name) }
                }
            }

} 

我尝试通过一些实验更改代码,但没有成功。

但是我得到了这个错误

Read from stdout: D:\PROJECTS\test\Project_VendorM8\app\models\Brand.scala:69: type mismatch; Read from stdout: found : scala.collection.immutable.Nil.type Read from stdout: required: scala.collection.mutable.Seq[(String, String)] D:\PROJECTS\test\Project_VendorM8\app\models\Brand.scala:69: type mismatch; found : scala.collection.immutable.Nil.type required: scala.collection.mutable.Seq[(String, String)] Read from stdout: foldLeftSeq[(String, String)] { (cs, c) => foldLeftSeq[(String, String)] { (cs, c) => Read from stdout: ^

改变

foldLeft[Seq[(String, String)]](Nil)

foldLeft(Seq.empty[(String, String)])

正如评论中所问,一个更简单的解决方案是否不仅仅是使用 map 和 write:

def options: Seq[(String,String)] = DB.withConnection { implicit connection =>
  SQL("select * from m_brand order by brandName").as(simple *)
    .map( b => (b.id.toString, b.name))
    .toSeq
}