scala,从 Some(value) 获取值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37884493/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 08:23:37  来源:igfitidea点击:

scala, get values from Some(value)

scala

提问by M.Hell

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

我目前正在尝试将自己读入 Scala。但我陷入了以下问题:

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("?

xml 属性被读取并转换为字符串,但被视为“Some(value)”。我已经尝试了几件事,但似乎没有一个工作,当我自己用“选项:字符串”(这是常见的解决方案)创建值时。有人知道摆脱“Some(”的简单方法吗?

Greetings Ma

问候马

回答by M.Olmsted

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.

您调用 toString 方法的值是一种Option[String]类型,而不是普通的String. 当有值时,你会得到Some(value),而如果没有值,你会得到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
}

回答by sumeet agrawal

You can apply get method on Some(value)

您可以在 Some(value) 上应用 get 方法

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

1238

回答by Nan Li

"Some().get" could return the real value. For example:

"Some().get" 可以返回实际值。例如:

val m = Map(("1", 2), (3, 4));
val a = m.get("1");
println(a.get + 1);

回答by M.Hell

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:

嗨,感谢您的投入。我把你的代码做了一些小的改动,node.seq, String, Some(String), Some[A]一开始的变量很混乱。它现在可以很好地使用这个简短版本:

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