在 Scala 中使用 bufferedInputStream 作为特征时的 Stackoverflow [英] Stackoverflow when use bufferedInputStream as a trait in scala
问题描述
我正在尝试解决Scala for the Impatient"一书给出的问题,该书要求将 java 的 BufferedInputStream 作为特征实现.这是我的实现,
I am trying to solve a problem given by the Book "Scala for the Impatient", which asked to implement java's BufferedInputStream as a trait. Here is my implementation,
trait Buffering {
this:InputStream =>
private[this] val bis = {
new JavaBufferedInputStream(this)
}
override def read = bis.read
override def read(byte:Array[Byte], off:Int, len:Int) = bis.read(byte, off, len)
override def available = bis.available
override def close() {
bis.close
}
override def skip(n:Long) = bis.skip(n)
}
def main(args:Array[String]) {
val bfis = new FileInputStream(new File("foo.txt")) with Buffering
println(bfis.read)
bfis.close
}
但是这给了我一个 java stackoverflow 错误,那么它有什么问题呢?谢谢!
But this give me a java stackoverflow error, so what's wrong with it? Thanks!
推荐答案
您似乎遇到了一个意想不到的堆栈溢出.解决这些问题的关键是查看堆栈跟踪的重复循环.它通常指向重复分配帧的内容.在这里它会显示类似的东西:
It looks like you are getting a stack overflow where you don't expect one. The key to troubleshoot these is to look at the repeating cycle of the stack trace. It usually points to what is repeatedly allocating frames. Here it will show something like that:
at C.Buffering$class.read(C.scala:12)
at C.C$$anon$1.read(C.scala:23)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:256)
at java.io.BufferedInputStream.read(BufferedInputStream.java:317)
at C.Buffering$class.read(C.scala:12)
at C.C$$anon$1.read(C.scala:23)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:256)
at java.io.BufferedInputStream.read(BufferedInputStream.java:317)
at C.Buffering$class.read(C.scala:12)
所以从下到上阅读,看起来你的 read(byte, ...)
正在调用 bis.read(byte, ...)
这是调用 BufferedInputStream.read
然后再次调用你的 read(byte, ...)
.
So reading from bottom to top, it looks like your read(byte, ...)
is calling bis.read(byte, ...)
which is calling BufferedInputStream.read
which is then calling your read(byte, ...)
again.
看起来 new BufferedInputStream(this)
正在调用底层 InputStream
上的 read
但是由于底层 this
code> 是您的对象,然后将调用委托给 bis
我们有无限递归.
It would appear that new BufferedInputStream(this)
is calling read
on the underlying InputStream
but since the underlying this
is your object that then delegates calls on bis
we have infinite recursion.
我猜作者希望你使用 abstract override
可堆叠修改模式,你可以使用 super
来引用正确的 read代码>方法.
I'm guessing that the author wants you to use the abstract override
stackable modifications pattern where you can use super
to refer to the right read
method.
这篇关于在 Scala 中使用 bufferedInputStream 作为特征时的 Stackoverflow的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!