我知道 Some 对象可以是 None 或我传递的对象之一。鉴于它不是 None 的事实,从 Some 对象中提取字段的理想方法是什么?我制作了一个“At”类,它的字段之一是“日期”。由于 Some 类具有与 Product 特征的混合,因此以下工作正常:
(An object with return type Some(At)).productElement(0).asInstanceOf[At].date
Run Code Online (Sandbox Code Playgroud)
但是有没有一种理想的方法来做到这一点?
我试图从字符串中检索用于创建枚举的案例对象
sealed trait Mapping {def code: Int;def desc: Symbol}
object types {
case object TypeA extends Mapping {
val code = 0;
val desc = 'A
}
case object TypeB extends Mapping {
val code = 1;
val desc = 'B
}
val values=List(TypeA,TypeB)
def getType(desc: Symbol) =
values.find(_.desc == desc)
}
Run Code Online (Sandbox Code Playgroud)
下面的代码使我能够从中回溯价值 Some(TypeA)
var s=types.getType('A)
Run Code Online (Sandbox Code Playgroud)
方法1
s match{
case Some(value)=>print(value.code)
}
Run Code Online (Sandbox Code Playgroud)
方法2
print(s.fold {-1} { x => x.code })
Run Code Online (Sandbox Code Playgroud)
以下是查询
None没有找到匹配项