问题
I am trying to retrieve case object used for creating enum from string
Taking reference from Extracting field from Some in Scala
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)
}
The below code makes me able to retrive value back from Some(TypeA)
var s=types.getType('A)
Approach 1
s match{
case Some(value)=>print(value.code)
}
Approach 2
print(s.fold {-1} { x => x.code })
Following are the queries
- I am not clear about the second approach Can anyone explain how fold is working here
- I want use a default type case object to represent
None
in case no match is found
回答1:
I am not clear about the second approach Can anyone explain how fold is working here
This is the signature of fold
:
def fold[B](ifEmpty: ⇒ B)(f: (A) ⇒ B): B
the first argument ifEmpty
is the "default" value that will be returned in case the Option
is empty, whereas the second argument f
is the function that gets executed on the value contained by the Option (if it's there).
opt.fold(a)(f)
is then equivalent to
opt.map(f).getOrElse(a)
or
opt match {
case None => a
case Some(v) => f(v)
}
I want use a default type case object to represent None in case no match is found
You can do something like:
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
}
case object DefaultType extends Mapping {
val code = -1
val desc = 'Default
}
val values = List(TypeA,TypeB)
def getType(desc: Symbol): Mapping =
values.find(_.desc == desc).getOrElse(DefaultType)
}
回答2:
If you just want to print out the contents, the way to go is
s.foreach(println(_.code))
s match{ case Some(value)=>print(value.code) }
Is a bad idea, because it will crash when
s
isNone
. You should add acase
clause to match that case (but again, you are better off just usingforeach
in this case).s.fold {-1} { x => x.code }
is equivalent tos.map(_.code).getOrElse(-1)
If you want default type instead of
None
you can just doprintln(s.getOrElse(DefaultType).code)
来源:https://stackoverflow.com/questions/45659351/retrieve-value-from-some-in-scala