2016-03-16 150 views
0

我想寫一個類型類來staticly編碼有什麼我可以輸出到PrinterScala的類型類派生的集合

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,但是在構建集合時這很有用;在這種情況下,我正在解構一個集合。

+1

好了,你的'Write'是不變的,這編譯'輸出(出,Set.empty [String] .toIterable)' –

+0

Doh!我以爲我有它:) – pathikrit

回答

2

你可以聲明類型參數的特質寫被逆變像這樣:

trait Write[-A] { 
    def apply(out: PrintWriter)(x: A): Unit 
} 

,然後這應該編譯