为什么 Some(1).getOrElse(Some(1)) 不是 Option[Int] 类型? [英] Why is Some(1).getOrElse(Some(1)) not of type Option[Int]?

查看:54
本文介绍了为什么 Some(1).getOrElse(Some(1)) 不是 Option[Int] 类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用 Scala 开展一个项目,但我似乎并不完全了解 Scala 的类型系统 :-/

I am currently working on a project with Scala and it seems I don't fully understand Scala's Typesystem :-/

我有以下情况:

def reviews(id: Int) = Action { implicit request =>
  Ok(html.products.reviews(
    reviewlist,
    reviewlist
      .find(review => review.id == id)
      .getOrElse(reviewlist.headOption)
  ))
}

可惜编译器说,他不能把Product转换成Option[Review],所以我改了代码

Unfortunately the compiler says, he cannot convert Product to Option[Review], so I changed the code

reviewlist
  .find(review => review.id == id)
  .getOrElse(reviewlist.headOption)

id match {
  case 0 => reviewlist.headOption
  case id => reviewlist.find(review => review.id == id)
}

现在似乎可以工作了,即使它与它不完全相同,例如,如果提交了无效的评论 ID,则不再显示第一条记录.然后它会假装没有可用的评论.

which seems to work now, even though its not exactly the same thing as it does, for example, not show the first record anymore if an invalid review id is being submitted. it will then pretend, that there are no reviews available yet.

然后我将问题分解为一个非常简单的示例:

I then broke the problem down to a veeery simple sample:

val a: Option[Int] = Some(1).getOrElse(Some(1))

那么,有没有人知道,为什么右侧的表达式不是 Option[Int] 类型??Some(1) 和 None 都直接从 Option 继承,这个表达式实际上是 Some(1) in any 还是我错了?

So, has anyone an idea, why the expression on the right side is not of the type Option[Int]?? Both, Some(1) and None inherit directly from Option and this expression is actually Some(1) in any or am I wrong?

足够有趣

val a: Option[Int] = None.getOrElse(None)

有效,但所有其他组合都无效...

works, but all other combinations do not...

推荐答案

你想要的:

val a: Option[Int] = Some(1).orElse(Some(1))

因为

x.getOrElse(y)

如果 x 是 Some(1)y(即 Some(1)),如果 x 是

将返回 1无,或用代码说话:

will return 1 if x is Some(1) or y (which is Some(1)) if x is None, or speaking in code:

if (Some(1).isDefined) 1 else Some(1)

这篇关于为什么 Some(1).getOrElse(Some(1)) 不是 Option[Int] 类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆