scala 在Scala中输出地图值的问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6385383/
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
Problem with outputting map values in scala
提问by Tom
I have the following code snippet:
我有以下代码片段:
val map = new LinkedHashMap[String,String]
map.put("City","Dallas")
println(map.get("City"))
This outputs Some(Dallas)instead of just Dallas. Whats the problem with my code ?
这输出Some(Dallas)而不仅仅是Dallas. 我的代码有什么问题?
Thank You
谢谢
回答by michael.kebe
Use the applymethod, it returns directly the Stringand throws a NoSuchElementExceptionif the key is not found:
使用该apply方法,它直接返回String,NoSuchElementException如果找不到key则抛出a :
scala> import scala.collection.mutable.LinkedHashMap
import scala.collection.mutable.LinkedHashMap
scala> val map = new LinkedHashMap[String,String]
map: scala.collection.mutable.LinkedHashMap[String,String] = Map()
scala> map.put("City","Dallas")
res2: Option[String] = None
scala> map("City")
res3: String = Dallas
回答by pedrofurla
It's not really a problem.
这不是问题。
While Java's Map version uses nullto indicate that a key don't have an associated value, Scala's Map[A,B].getreturns a Options[B], which can be Some[B]or None, and None plays a similar role to java's null.
虽然 Java 的 Map 版本用于null指示键没有关联的值,但 ScalaMap[A,B].get返回 a Options[B],它可以是Some[B]或None,并且 None 与 java 的null.
REPL session showing why this is useful:
REPL 会话显示了为什么这很有用:
scala> map.get("State")
res6: Option[String] = None
scala> map.get("State").getOrElse("Texas")
res7: String = Texas
Or the not recommended but simple get:
或者不推荐但简单的get:
scala> map.get("City").get
res8: String = Dallas
scala> map.get("State").get
java.util.NoSuchElementException: None.get
at scala.None$.get(Option.scala:262)
Check the Optiondocumentation for more goodies.
查看Option文档以获取更多好东西。
回答by notan3xit
There are two more ways you can handle Optionresults.
还有两种方法可以处理Option结果。
You can pattern match them:
您可以模式匹配它们:
scala> map.get("City") match {
| case Some(value) => println(value)
| case _ => println("found nothing")
| }
Dallas
Or there is another neat approach that appears somewhere in Programming in Scala. Use foreachto process the result. If a result is of type Some, then it will be used. Otherwise (if it's None), nothing happens:
或者在Programming in Scala中出现了另一种巧妙的方法。使用foreach处理结果。如果结果的类型为Some,则将使用它。否则(如果是None),什么都不会发生:
scala> map.get("City").foreach(println)
Dallas
scala> map.get("Town").foreach(println)

