为什么在嵌套的Iterator上展平,为什么我需要类型归属?

问题描述 投票:5回答:2
(new Iterator[List[Int]] {
  def hasNext: Boolean = ???
  def next(): List[Int] = ???
}).flatten

给出错误:

value flatten is not a member of Iterator[List[Int]]
[error] possible cause: maybe a semicolon is missing before `value flatten'?
[error]     }.flatten
[error]       ^
[error] one error found

但是

(new Iterator[List[Int]] {
  def hasNext: Boolean = ???
  def next(): List[Int] = ???
}: Iterator[List[Int]]).flatten

作品。也将迭代器存储在val中。

Scala版本:2.11.8

scala type-inference ascription
2个回答
1
投票

我认为它试图解析此:

new Iterator[List[Int]] {
      def hasNext: Boolean = ???
      def next(): List[Int] = ???
    }.flatten

原样

new Iterator[List[Int]] ( {
      def hasNext: Boolean = ???
      def next(): List[Int] = ???
    }.flatten )

注意在括号()的位置。


0
投票

似乎在2.11和2.12中都与隐式分辨率有关。如果您通过

显式导入flatten扩展方法
import scala.collection.TraversableOnce.flattenTraversableOnce

然后似乎有效。自2.13.0-M3以来,该问题似乎已得到解决,其中打字机阶段给出了

collection.this.TraversableOnce.flattenTraversableOnce[Int, List]({
  final class $anon extends AnyRef with Iterator[List[Int]] {
    def <init>(): <$anon: Iterator[List[Int]]> = {
      $anon.super.<init>();
      ()
    };
    def hasNext: Boolean = scala.Predef.???;
    def next(): List[Int] = scala.Predef.???
  };
  new $anon()
})(scala.Predef.$conforms[List[Int]]).flatten

在2.13.0版本flatten中似乎不再通过扩展方法提供

{
  final class $anon extends AnyRef with Iterator[List[Int]] {
    def <init>(): <$anon: Iterator[List[Int]]> = {
      $anon.super.<init>();
      ()
    };
    def hasNext: Boolean = scala.Predef.???;
    def next(): List[Int] = scala.Predef.???
  };
  new $anon()
}.flatten[Int](scala.Predef.$conforms[List[Int]])

上述扩展似乎由SLS 6.4 Designators解释

𝑒.𝑥的键入就像是{val𝑦=𝑒; 𝑦.𝑥}

© www.soinside.com 2019 - 2024. All rights reserved.