我目前正在尝试了解Scala(2.10.2)迭代器及其行为。我有兴趣使用filter
和map
这样的方法,根据互联网上的不同地方,这些方法是懒惰实施的,这很有帮助。
但是,当我实现Iterator [T]接口时,在其上调用filter
会抛出java.lang.AbstractMethodError
。任何人都能说明原因吗?
一个例子:
class SillyIterator extends Iterator[Int]
{
private var i = 0
def hasNext : Boolean = i < 10
def next() : Int =
{
val ret = i
i += 1
ret
}
}
然后在控制台中:
scala> new SillyIterator
res20: SillyIterator = SillyIterator@4659d97
scala> res20.filter( _ > 3 )
java.lang.AbstractMethodError: SillyIterator.filter(Lscala/Function1;)Lscala/collection/Iterator;
...
编辑:
这不是由粘贴模式问题引起的。如果我将整个类定义为单行,它仍然会失败:
scala> class SillyIterator extends Iterator[Int]{ private var i = 0; def hasNext : Boolean = i < 10; def next() : Int = { val ret = i; i += 1; ret } }
defined class SillyIterator
scala> val s = new SillyIterator
s: SillyIterator = SillyIterator@5bf1effb
scala> s.next
res0: Int = 0
scala> s.filter( _ < 3 )
java.lang.AbstractMethodError: SillyIterator.filter(Lscala/Function1;)Lscala/collection/Iterator;
at .<init>(<console>:13)
...
答案 0 :(得分:0)
您的代码在IDE中应该可以正常工作,但在工作表和REPL中可能存在一些问题。
要避免这些问题,只需将支架移动到第一行即可。像这样:
class SillyIterator extends Iterator[Int]{
private var i = 0
def hasNext : Boolean = i < 10
def next() : Int = {
val ret = i
i += 1
ret
}
}
在您的情况下,您有类SillyIterator的定义
class SillyIterator extends Iterator[Int]
后面是花括号中的代码块。
答案 1 :(得分:0)
您的代码在REPL中工作正常,您不需要提升大括号(虽然我个人觉得这种语法很烦人),您需要做的是使用:pa
进入粘贴模式:
scala> :pa
// Entering paste mode (ctrl-D to finish)
class SillyIterator extends Iterator[Int]
{
private var i = 0
def hasNext : Boolean = i < 10
def next() : Int =
{
val ret = i
i += 1
ret
}
}
// Exiting paste mode, now interpreting.
defined class SillyIterator
scala> new SillyIterator
res15: SillyIterator = non-empty iterator
scala> res15.filter( _ > 3 )
res16: Iterator[Int] = non-empty iterator
scala> res15.filter( _ > 3 ).toList
res17: List[Int] = List(5, 6, 7, 8, 9)
如果您不使用粘贴模式,则新行将在REPL中生效,如果您不使用它,则会获得此结果(或者在大括号的上方移动):< / p>
scala> class SillyIterator extends Iterator[Int]
<console>:7: error: class SillyIterator needs to be abstract, since:
it has 2 unimplemented members.
/** As seen from class SillyIterator, the missing signatures are as follows.
* For convenience, these are usable as stub implementations.
*/
...