【发布时间】:2015-01-27 02:46:13
【问题描述】:
就在我以为我理解了 Scala 类型系统的基础知识的时候...:/
我正在尝试实现一个读取文件内容并输出一组记录的类。一条记录可能是一行,但也可能是一个字节块或任何东西。所以我追求的是一种结构,它允许 Reader 的类型暗示 Record 的类型,这反过来又暗示要使用正确的 Parser。
只要MainApp.records(f) 只返回一种类型的阅读器,这个结构就可以工作。只要它可以返回更多,我就会收到此错误:
找不到参数解析器的隐式值
我认为问题在于顶部的类型化特征定义,但我不知道如何解决这个问题......
// Core traits
trait Record[T]
trait Reader[T] extends Iterable[Record[T]]
trait Parser[T] {
def parse(r: Record[T]): Option[Int]
}
// Concrete implementations
class LineRecord[T] extends Record[T]
class FileReader[T](f:File) extends Reader[T] {
val lines = Source.fromFile(f).getLines()
def iterator: Iterator[LineRecord[T]] =
new Iterator[LineRecord[T]] {
def next() = new LineRecord[T]
def hasNext = lines.hasNext
}
}
trait TypeA
object TypeA {
implicit object TypeAParser extends Parser[TypeA] {
def parse(r: Record[TypeA]): Option[Int] = ???
}
}
trait TypeB
object TypeB {
implicit object TypeBParser extends Parser[TypeB] {
def parse(r: Record[TypeB]): Option[Int] = ???
}
}
// The "app"
object MainApp {
def process(f: File) =
records(f) foreach { r => parse(r) }
def records(f: File) = {
if(true)
new FileReader[TypeA](f)
else
new FileReader[TypeB](f)
}
def parse[T](r: Record[T])(implicit parser: Parser[T]): Option[Int] =
parser.parse(r)
}
【问题讨论】: