Scala初始化空堆栈

时间:2016-01-11 16:22:56

标签: scala

我在Scala中有以下结构:

\xx

我正在尝试将所有堆栈初始化为空。

但是,我收到以下错误:

var pos = new HashMap[Char, Stack[Int]] withDefaultValue Stack[Int].empty

如果我尝试删除元素类型信息:

Solution.scala:11: error: missing arguments for method apply in class GenericCompanion;
follow this method with `_' if you want to treat it as a partially applied function
        var pos = new HashMap[Char, Stack[Int]] withDefaultValue Stack[Int].empty

它也失败了:

var pos = new HashMap[Char, Stack[Int]] withDefaultValue Stack.empty

我正在使用可变集合:

Solution.scala:11: error: type mismatch;
 found   : scala.collection.mutable.Stack[Nothing]
 required: scala.collection.mutable.Stack[Int]
Note: Nothing <: Int, but class Stack is invariant in type A.
You may wish to investigate a wildcard type such as `_ <: Int`. (SLS 3.2.10)
        var pos = new HashMap[Char, Stack[Int]] withDefaultValue Stack.empty

如何将堆栈初始化为空?

1 个答案:

答案 0 :(得分:4)

empty是随附Stack对象的通用方法,因此您需要为其提供类型参数,否则您会收到Stack[Nothing]

使用Stack.empty[Int]

var pos = new HashMap[Char, Stack[Int]] withDefaultValue Stack.empty[Int]