斯卡拉MongoDB:可选字段和不可变字段

发布于 2024-10-08 07:04:29 字数 824 浏览 4 评论 0原文

我有这个域对象:

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]                           ^

这有什么问题?

I have this domain object:

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

with the age optional field. So I defined my factory:

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)
}

but it does not compile, since I get:

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

What is wrong with this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

雄赳赳气昂昂 2024-10-15 07:04:29

也许,你可以写

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

maybe, you could write

override def factory(dbo: DBObject): Option[Person] = 
    for {
      n <- name from dbo
      z <- email from dbo
    } yield new Person(n, age from dbo, z)
阪姬 2024-10-15 07:04:29

amsayk 答案的一个变体,但稍微更对称

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

A variant of amsayk's answer, but slightly more symmetrical

for {
      n <- name from dbo
      t = age from dbo
      z <- email from dbo
    } yield new Person(n, t, z)
沧桑㈠ 2024-10-15 07:04:29

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

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

You need to wrap t in a Some object

} yield new Person(n, Some(t), z)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文