【问题标题】:Scala case class Option value chainingScala 案例类 Option 值链
【发布时间】:2018-06-07 11:13:26
【问题描述】:
case class Person(@BsonProperty("first_name") firstName:Option[String],@BsonProperty("second_name")  secondName:Option[String],@BsonProperty("person_age") var  age:Int)


val me = Some(Person(Some(Ambareesh),Some(B),23))

      Or

val me = None

      Or

val me = Some(Person(Some(Ambareesh),None,23))

     Or

val me = Some(Person(None,None,23))


someOperation(me.secondName / None) //How can I implement this behavior in single line.
someOperation(me.firstName / None)


def someOperation(name:Option[String]){
   //Do ...
 }

我对方法someOperation 的论点(Person 的实例)表示怀疑。参数本身是一个选项值,字段也是选项。如果其中任何一个是 None(argument or argument.fieldName) 我希望 None 作为返回,否则将字段值作为 Some(fieldValue)。有可能吗?

【问题讨论】:

  • 对不起。我无法理解这个问题
  • val me = Some(Person(Some(Ambareesh),Some(B),23))。 me.get.firstName.get 应该返回 None / firstName 即 Option[String] 类似 me.get.secondName.get。我有更多参数,例如 firstName 和 secondName,所以我应该能够在函数调用本身中引用它。
  • me.firstName 不是已经是Option了吗?
  • @Jatin 不,me.firstName 无法编译。
  • 是的,如果我不是 None,me.get.firstName 会起作用。

标签: scala scala-collections


【解决方案1】:
someOperation(me.flatMap(_.secondName))

见ScalaDoc。

您可以将map 用于非Option 属性:me.map(_.age) 是Option[Int]。

【讨论】:

    【解决方案2】:

    如果您的 someOperation 返回一个选项,您也可以使用 for 理解。

    val result: Option[String] = for {
       person <- me
       firstName <- someOperation(person.firstName)
       secondName<- someOperation(person.secondName)
    } yield <use firstName, secondName here>
    

    这将为您提供您想要计算的任何结果或None。

    【讨论】:

    • 但me 可以是None。我已经编辑了这个问题,澄清了这一点。
    • 是的,这对理解力没有影响,你最终只会得到 None 。使用这个或任何其他答案只是风格问题,因为有很多方法可以解决这个问题。
    【解决方案3】:

    据我了解,您需要提取人员字段并将其传递给方法 someOperation。对吧?

    如果是这样,您可以为此使用模式匹配:

    someOperation(
      me match {
        case Some(person) => person.firstName
        case None => None
      } 
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-27
      • 2014-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-03
      • 1970-01-01
      相关资源
      最近更新 更多