Scala 案例 class 期权价值链
Scala case class Option value chaining
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.fieldName),我希望 None
作为 return,否则字段值作为 Some(fieldValue)。可能吗?
据我了解,您需要提取人员字段并将其传递给方法 someOperation。对吗?
如果是这样,您可以为此使用模式匹配:
someOperation(
me match {
case Some(person) => person.firstName
case None => None
}
)
someOperation(me.flatMap(_.secondName))
见ScalaDoc。
您可以将 map
用于非 Option
属性:me.map(_.age)
是 Option[Int]
。
如果您的 someOperation
returns 一个选项,您也可以使用 for
理解。
val result: Option[String] = for {
person <- me
firstName <- someOperation(person.firstName)
secondName<- someOperation(person.secondName)
} yield <use firstName, secondName here>
这将为您提供您想要计算的任何结果或 None
。
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.fieldName),我希望 None
作为 return,否则字段值作为 Some(fieldValue)。可能吗?
据我了解,您需要提取人员字段并将其传递给方法 someOperation。对吗?
如果是这样,您可以为此使用模式匹配:
someOperation(
me match {
case Some(person) => person.firstName
case None => None
}
)
someOperation(me.flatMap(_.secondName))
见ScalaDoc。
您可以将 map
用于非 Option
属性:me.map(_.age)
是 Option[Int]
。
如果您的 someOperation
returns 一个选项,您也可以使用 for
理解。
val result: Option[String] = for {
person <- me
firstName <- someOperation(person.firstName)
secondName<- someOperation(person.secondName)
} yield <use firstName, secondName here>
这将为您提供您想要计算的任何结果或 None
。