我想写一个类型类来静态编码我可以输出的Printer
:
import java.io.PrintWriter
trait Write[A] {
def apply(out: PrintWriter)(x: A): Unit
}
object Write {
def apply[A] = new Write[A] {
def apply(out: PrintWriter)(x: A) = out.print(x)
}
implicit val string : Write[String] = Write[String]
implicit val char : Write[Char] = Write[Char]
implicit val boolean : Write[Boolean] = Write[Boolean]
implicit val int : Write[Int] = Write[Int]
implicit val long : Write[Long] = Write[Long]
implicit val bigInt : Write[BigInt] = Write[BigInt]
implicit val double : Write[Double] = Write[Double]
implicit val bigDecimal : Write[BigDecimal] = Write[BigDecimal]
}
现在我可以写下这个:
def output[A(out: PrintWriter, x: A)(implicit write: Write[A]) = write(out)(x)
output(out, "hello") // compiles
output(out, 1) //compiles
output(out, Set.empty[String]) // does not compile
但是,现在我想为所有Write
s写一个Iterable
:
implicit def iterable[A](implicit write: Write[A]) = new Write[Iterable[A]] {
def apply(out: PrintWriter)(xs: Iterable[A]) = {
xs.foreach(write(out))
out.println()
}
}
但是,我仍然无法编译:
output(out, Set.empty[String]) // should compile!!
理想情况下,我应该能够导出嵌套的迭代,例如:
output(out, Array.ofDim[Int](100, 100)) // should compile!!
我该怎么办?我查看了CanBuild
,但在构建集合时这很有用;在这种情况下,我正在解构一个集合。
答案 0 :(得分:2)
您可以在特征中声明类型参数A写为逆变,如下所示:
trait Write[-A] {
def apply(out: PrintWriter)(x: A): Unit
}
然后应该编译