scala, get values from Some(value)

2019-09-21 21:52发布

问题:

i am currently trying to read myself into scala. But i got stuck on the following:

val value: String = properties(j).attribute("value").toString
print(value)

The xml property is read and converted to a string, but gets viewed as "Some(value)". I have tried several things but none seems to work when not i myself created the value with "Option: String"(which was the common solution). Does somebody know an easy way to get rid of the "Some("?

Greetings Ma

回答1:

The value you're calling the toString method on is an Option[String] type, as opposed to a plain String. When there is a value, you'll get Some(value), while if there's not a value, you'll get None.

Because of that, you need to handle the two possible cases you may get back. Usually that's done with a match:

val value: String = properties(j).attribute("value") match {
  case None => ""//Or handle the lack of a value another way: throw an error, etc.
  case Some(s: String) => s //return the string to set your value
}


回答2:

You can apply get method on Some(value)

object Example {
  def main(args: Array[String]) = {
    val vanillaDonut: Donut = Donut("Vanilla", 1.50)
    val vanillaDonut1: Donut = Donut("ChocoBar", 1.50,Some(1238L))
    println(vanillaDonut.name)
    println(vanillaDonut.productCode)
    println(vanillaDonut1.name)
    println(vanillaDonut1.productCode.get)

  }

}
case class Donut(name: String, price: Double, productCode: Option[Long] = None)

Result:- Vanilla

None

ChocoBar

1238



回答3:

Hi and thanks for the input. I took your code with minor changes, and it was quite confusing with the variables node.seq, String, Some(String), Some[A] in the beginning. It works now quite fine with this short version:

  val value = properties(j).attribute("value") match {
              case None => ""
              case Some(s) => s //return the string to set your value
            }


标签: scala