找到选项[CSVWriter]但需要CSVWriter? `var`造成了这个问题?

时间:2017-05-26 22:25:27

标签: scala

以下代码

var writers = new HashMap[String, CSVWriter]()

  var writer = writers.get(pool)
  if (writer == null) {
    //writer = new CSVWriter(new FileWriter(s"..."))
    writers.put(pool, writer) // Errr
  }

错误

[error]  found   : Option[au.com.bytecode.opencsv.CSVWriter]
[error]  required: au.com.bytecode.opencsv.CSVWriter
[error]         writers.put(pool, writer)
[error]                           ^
[error] one error found

var会自动添加Option包装吗?我应该怎样做才能将CSVWriter放在hashmap中?

1 个答案:

答案 0 :(得分:0)

使用.get(key)从scala中的HashMap检索值时,默认返回值为Option instance。

scala> val writers = collection.mutable.HashMap("abc" -> "def")
writers: scala.collection.mutable.HashMap[String,String] = Map(abc -> def)

scala> writers.get("abc")
res10: Option[String] = Some(def)

如果密钥存在于HashMap中,则选项将返回某个实例,如果密钥不存在,则返回None。

scala> writers.get("a")
res13: Option[String] = None

这有助于避免nullpointer异常。

我们需要使用另一个get

来获得真正的价值
scala> writers.get("abc").get
res11: String = def

但为了安全起见,我们可以使用getOrElse

scala> writers.getOrElse("abc", "no value")
res1: String = def

scala> writers.getOrElse("a", "no value")
res2: String = no value

我希望解释清楚