开发者

How can I override Iterable.flatMap in Scala 2.9.0?

开发者 https://www.devze.com 2023-03-05 07:05 出处:网络
I\'m just updating some of my code to 2.9.0, and I\'ve run into a problem. I have a trait that I call \"NonStrictIterable\" (essentially, everything should be as lazy as possible --- no code outside N

I'm just updating some of my code to 2.9.0, and I've run into a problem. I have a trait that I call "NonStrictIterable" (essentially, everything should be as lazy as possible --- no code outside NonStrictIterable itself should run until someone actually asks for an element).

In 2.9.0, I don't seem to be able to override flatMap, however. Here's a cut down version, that exhibits the error:

import scala.collection.generic.CanBuildFrom

trait NonStrictIterable[A] extends Iterable[A] { self =>
  def iterator: Iterator[A]

  override def flatMap[B, That](f: A => TraversableOnce[B])(implicit bf: CanBuildFrom[Iterable[A], B, That]): That = {
    new NonStrictIterable[B] {
      def iterator = self.iterator flatMap { a: A => f(a).toIterable.iterator }
    }.asInstanceOf[That]
  }
}

This used to work pre 2.9.0, but now I get "method flatMap overrides nothing". Looking up the method signature for Iterable.flatMap, I see that TraversableOnce in the type signature has changed to enTraversableOnce. Making the 开发者_运维知识库corresponding change

import scala.collection.GenTraversableOnce
import scala.collection.generic.CanBuildFrom

trait NonStrictIterable[A] extends Iterable[A] { self =>
  def iterator: Iterator[A]

  override def flatMap[B, That](f: A => GenTraversableOnce[B])(implicit bf: CanBuildFrom[Iterable[A], B, That]): That = {
    new NonStrictIterable[B] {
      def iterator = self.iterator flatMap { a: A => f(a).toIterable.iterator }
    }.asInstanceOf[That]
  }
}

I get the compiler error "erroneous or inaccessible type".

What's going on? Can someone suggest a workaround?


You need to upgrade to 2.9 final. This was an error in a previous RC which has been fixed.


Works for me. I suspect that you are actually compiling against scala-library.jar from RC3.

 ~/code/scalaz[scala-2.9.x*]: scala29
Welcome to Scala version 2.9.0.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_22).
Type in expressions to have them evaluated.
Type :help for more information.

scala> import scala.collection.GenTraversableOnce
import scala.collection.GenTraversableOnce

scala> import scala.collection.generic.CanBuildFrom
import scala.collection.generic.CanBuildFrom

scala> 

scala> trait NonStrictIterable[A] extends Iterable[A] { self =>
     |  def iterator: Iterator[A]
     | 
     |  override def flatMap[B, That](f: A =>
     | GenTraversableOnce[B])(implicit bf: CanBuildFrom[Iterable[A], B,
     | That]): That = {
     |    new NonStrictIterable[B] {
     |      def iterator = self.iterator flatMap { a: A => f(a).toIterable.iterator }
     |    }.asInstanceOf[That]
     |  }
     | }
defined trait NonStrictIterable
0

精彩评论

暂无评论...
验证码 换一张
取 消