Retrieve value from Some in scala

为君一笑 提交于 2020-08-08 08:42:06

问题


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

  1. I am not clear about the second approach Can anyone explain how fold is working here
  2. 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:


  1. If you just want to print out the contents, the way to go is s.foreach(println(_.code))

  2. 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).

  3. s.fold {-1} { x => x.code } is equivalent to s.map(_.code).getOrElse(-1)

  4. If you want default type instead of None you can just do println(s.getOrElse(DefaultType).code)



来源:https://stackoverflow.com/questions/45659351/retrieve-value-from-some-in-scala

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!