[英]Problem with outputting map values in scala
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
. 这输出Some(Dallas)
而不仅仅是Dallas
。 Whats the problem with my code ? 我的代码有问题吗?
Thank You 谢谢
Use the apply
method, it returns directly the String
and throws a NoSuchElementException
if the key is not found: 使用apply
方法,它直接返回String
并在未找到密钥时抛出NoSuchElementException
:
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
It's not really a problem. 这不是一个真正的问题。
While Java's Map version uses null
to indicate that a key don't have an associated value, Scala's Map[A,B].get
returns a Options[B]
, which can be Some[B]
or None
, and None plays a similar role to java's null
. 虽然Java的Map版本使用null
来表示某个键没有关联的值,但Scala的Map[A,B].get
返回一个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 Option documentation for more goodies. 查看Option文档以获取更多好处。
There are two more ways you can handle Option
results. 您还可以通过两种方式处理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 . 或者在Scala编程中出现了另一种巧妙的方法。 Use foreach
to process the result. 使用foreach
处理结果。 If a result is of type Some
, then it will be used. 如果结果是Some
类型,则将使用它。 Otherwise (if it's None
), nothing happens: 否则(如果它是None
),没有任何反应:
scala> map.get("City").foreach(println)
Dallas
scala> map.get("Town").foreach(println)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.