Scala 为什么嵌套迭代器上的扁平化不编译,为什么我需要类型归属?

Scala 为什么嵌套迭代器上的扁平化不编译,为什么我需要类型归属?,scala,type-inference,ascription,Scala,Type Inference,Ascription,给出错误: (new Iterator[List[Int]] { def hasNext: Boolean = ??? def next(): List[Int] = ??? }).flatten 但是 工作。将迭代器存储在val中同样有效 Scala版本:2.11.8我认为它试图解析以下内容: 新迭代器[List[Int]]{ def hasNext:Boolean=??? def next():列表[Int]=??? }.压扁 就这样 新迭代器[List[Int]]{ def h

给出错误:

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

工作。将迭代器存储在val中同样有效


Scala版本:2.11.8

我认为它试图解析以下内容:

新迭代器[List[Int]]{
def hasNext:Boolean=???
def next():列表[Int]=???
}.压扁
就这样

新迭代器[List[Int]]{
def hasNext:Boolean=???
def next():列表[Int]=???
}(扁平化)

注意我在哪里添加了括号
()

我相信这个问题已经被解决了。这个问题与匿名类相伴而生,匿名类不适合隐式搜索

我认为aaf9198#diff-7c03397456d3b987549fd039d6b639c6R516是 首先要排除细化/anon类对 它的同伴@奥德斯基你还记得动机吗

这是一个极小的复制品

(new Iterator[List[Int]] {
  def hasNext: Boolean = ???
  def next(): List[Int] = ???
}: Iterator[List[Int]]).flatten
因此,由于在2.11和2.12中,
Iterator上的
flatten
作为一种扩展方法提供,因此问题将针对匿名
Iterator
类显示


以下是我在进行上述编辑之前的回答:

这似乎与2.11和2.12中的隐含分辨率有关。如果通过显式导入
展平
作为扩展方法

trait A {
  def foo(): Int
}
class B {
  def bar(): String = "woohoo"
}
object A {
  implicit def aToB(a: A): B = new B
}

(new A {
  override def foo(): Int = 42
}).bar()

// Error: 
// value bar is not a member of A$A12.this.A 
// possible cause: maybe a semicolon is missing before `value bar'? }).bar();
然后它似乎起作用了。这个问题似乎是从2.13.0-M3开始解决的,打字机阶段给出

import scala.collection.TraversableOnce.flattenTraversableOnce
上述扩展似乎是由


在整个迭代器周围添加参数会得到相同的结果(编辑的OP)。
import scala.collection.TraversableOnce.flattenTraversableOnce
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

{
  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]])