0
我想寫一個類型類來staticly編碼有什麼我可以輸出到Printer
:Scala的類型類派生的集合
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
所有Iterable
S:
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!!
,我應該能夠導出嵌套iterables太例如: -
output(out, Array.ofDim[Int](100, 100)) // should compile!!
我該怎麼辦?我查看了CanBuild
,但是在構建集合時這很有用;在這種情況下,我正在解構一個集合。
好了,你的'Write'是不變的,這編譯'輸出(出,Set.empty [String] .toIterable)' –
Doh!我以爲我有它:) – pathikrit