Reputation: 2393
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
None
in case no match is foundUpvotes: 2
Views: 2247
Reputation: 40500
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
is None
. You should add a case
clause to match that case (but again, you are better off just using foreach
in this case).
s.fold {-1} { x => x.code }
is equivalent to s.map(_.code).getOrElse(-1)
If you want default type instead of None
you can just do println(s.getOrElse(DefaultType).code)
Upvotes: 4
Reputation: 108101
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)
}
Upvotes: 6