【问题标题】:Scala's type inference with Sets behaves... strangely? [duplicate]Scala 对 Sets 的类型推断的行为……很奇怪? [复制]
【发布时间】:2013-10-20 22:02:46
【问题描述】:

看起来很奇怪,但这不起作用:

scala> (1 to 6).toSet map (_ / 2)
<console>:8: error: missing parameter type for expanded function ((x$1) => x$1.$div(2))
              (1 to 6).toSet map (_ / 2)
                                  ^

但是,使用 to[Set] 而不是 toSet 会:

scala> (1 to 6).to[Set] map (_ / 2)
res0: scala.collection.immutable.Set[Int] = Set(2, 0, 3, 1)

嗯。 o_O

还认为这是可行的:

scala> val s = (1 to 6).toSet; s map (_ / 2)
s: scala.collection.immutable.Set[Int] = Set(5, 1, 6, 2, 3, 4)
res1: scala.collection.immutable.Set[Int] = Set(2, 0, 3, 1)

正如@AlexIv 所建议的那样,Range.Inclusive 是一阶类型,请记住,这也不适用于List[Int]

scala> List(1, 2, 3, 4, 5, 6).toSet map (_ / 2)
<console>:8: error: missing parameter type for expanded function ((x$1) => x$1.$
div(2))
              List(1, 2, 3, 4, 5, 6).toSet map (_ / 2)
                                                ^

和以前一样,这是可行的:

scala> val s = List[Int](1, 2, 3, 4, 5, 6).toSet; s map (_ / 2)
s: scala.collection.immutable.Set[Int] = Set(5, 1, 6, 2, 3, 4)
res3: scala.collection.immutable.Set[Int] = Set(2, 0, 3, 1)

编辑Type inference fails on Set made with .toSet?的副本

【问题讨论】:

标签: scala type-inference scala-collections


【解决方案1】:

打字机阶段 (scala -Xprint:typer) 隐藏了答案:

private[this] val res7: <error> = Predef.intWrapper(1).to(6).toSet[B].map[B, That]({
  ((x: Nothing) => Predef.identity[Nothing](x))
})();

(1 to 6) 返回一个 Range.Inclusive,它是一阶类型而不是类型构造函数,它没有参数化,但 Set[A] 期望/要求您为其提供某种类型并返回一个类型。当您调用toSet 时,scalac 需要某种类型,因为Inclusive 没有toSet 方法,它继承自TraversableOnce 并且是一个泛型方法,因此您需要显式提供某种类型:

(1 to 6).toSet[Int].map(identity)
res0: scala.collection.immutable.Set[Int] = Set(5, 1, 6, 2, 3, 4)

toBuffer 也不起作用,其他转换完美,这两种方法有类似的实现:

def toBuffer[B >: A]: mutable.Buffer[B] = to[ArrayBuffer].asInstanceOf[mutable.Buffer[B]]

def toSet[B >: A]: immutable.Set[B] = to[immutable.Set].asInstanceOf[immutable.Set[B]]

【讨论】:

  • 好的。但这也不适用于作为类型构造函数的 List[Int]。 (更新问题。)
  • @MichałRus 我添加了一些信息。方法toSettoBuffer 需要一个类型参数,它的下限为A。所以推断为toSet[B &gt;: Int]
猜你喜欢
  • 1970-01-01
  • 2016-02-29
  • 2020-08-12
  • 2019-04-27
  • 2013-06-10
  • 2021-01-05
  • 2019-05-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多