【问题标题】:Scala initialize empty stacksScala初始化空栈
【发布时间】:2016-01-11 16:22:56
【问题描述】:

我在 Scala 中有以下结构:

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

我正在使用可变集合:

import collection.mutable._

如何将堆栈初始化为空?

【问题讨论】:

    标签: scala


    【解决方案1】:

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

    使用Stack.empty[Int]

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

    【讨论】:

      猜你喜欢
      • 2016-01-29
      • 2015-08-14
      • 2022-01-12
      • 1970-01-01
      • 2012-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-18
      相关资源
      最近更新 更多