Scala + MongoDB:可选字段和不可变字符

时间:2010-12-17 15:53:44

标签: scala mongodb immutability mongo-scala-driver

我有这个域名对象:

case class Person (
  name : String,
  age: Option[Int],
  email : String
) extends MongoObject

带有年龄可选字段。所以我定义了我的工厂:

object Person extends MongoObjectShape[Person] {
  lazy val name = Field.scalar("name", _.name)
  lazy val age = Field.optional("age", t => t.age)
  lazy val email = Field.scalar("email", _.email)

  override lazy val * = name :: age :: email :: Nil
  override def factory(dbo: DBObject): Option[Person] = 
    for {
      n <- name from dbo
      t <- age from dbo
      z <- email from dbo
    } yield new Person(n, t, z)
}

但它没有编译,因为我得到:

[error]  found   : Int
[error]  required: Option[Int]
[error]     } yield new Person(n, t, z)
[error]                           ^

这有什么问题?

3 个答案:

答案 0 :(得分:4)

也许,你可以写

override def factory(dbo: DBObject): Option[Person] = 
    for {
      n <- name from dbo
      z <- email from dbo
    } yield new Person(n, age from dbo, z)

答案 1 :(得分:3)

amsayk答案的变体,但略微更对称

for {
      n <- name from dbo
      t = age from dbo
      z <- email from dbo
    } yield new Person(n, t, z)

答案 2 :(得分:1)

您需要将T包装在Some对象中

} yield new Person(n, Some(t), z)