2015-06-10 144 views
0

我試圖向scala.collection.Iterable trait添加功能,更具體地說,是一個迭代遍歷元素並打印出來的printerate函數(如果存在沒有參數,否則輸出流參數)。我正在使用爲對象printSelf()創建的預定義擴展方法。但是,這會導致編譯器錯誤,「值printSelf不是類型參數Object的成員。」我也想把它作爲一個單獨的文件,這樣我就可以輕鬆地在幾個項目和應用程序之間使用。Scala隱式類型使用類型參數轉換類

這是我爲我的轉換文件當前的代碼:

import java.io.OutputStream 
import scala.collection.Iterable 

package conversion{ 
    class Convert { 
    implicit def object2SuperObject(o:Object) = new ConvertObject(o) 
    implicit def iterable2SuperIterable[Object](i:Iterable[Object]) = new ConvertIterable[Object](i) 
    } 
    class ConvertObject(o:Object){ 
    def printSelf(){ 
     println(o.toString()) 
    } 
    def printSelf(os:OutputStream){ 
     os.write(o.toString().getBytes()) 
    } 
    } 
    class ConvertIterable[Object](i:Iterable[Object]){ 
    def printerate(){ 
     i.foreach {x => x.printSelf() } 
    } 
    def printerate(os:OutputStream){ 
     i.foreach { x => x.printSelf(os) } 
    } 
    } 
} 

我也越來越在正試圖測試此代碼類似的錯誤,「價值printerate不是scala.collection的成員。 immutable.Range':

import conversion.Convert 
package test { 
    object program extends App { 
    new testObj(10) test 
    } 
    class testObj(i: Integer) { 
    def test(){ 
     val range = 0.until(i) 
     0.until(i).printerate() 
    } 
    } 
} 

我接近此類型轉換的方式有什麼問題?

+0

作爲一個樣式注意,可以考慮使用隱式類,而不是對象,具有隱含DEFS:HTTP://docs.scala- lang.org/overviews/core/implicit-classes.html。 – Gal

回答

2

其實有幾件事情:

  1. 轉換應該是一個對象,而不是一類。
  2. 您使用對象,而不是任何
  3. 您使用對象作爲泛型類型標識符,而不是更混亂T.
  4. 不會導入隱含的定義(這是不夠的導入對象本身)。

這應該工作:

package conversion { 
    object Convert { 
    implicit def object2SuperObject(o: Any) = new ConvertObject(o) 
    implicit def iterable2SuperIterable[T](i:Iterable[T]) = new ConvertIterable[T](i) 
    } 
    class ConvertObject(o: Any){ 
    def printSelf(){ 
     println(o.toString()) 
    } 
    def printSelf(os:OutputStream){ 
     os.write(o.toString().getBytes()) 
    } 
    } 
    class ConvertIterable[T](i:Iterable[T]){ 
    import Convert.object2SuperObject 
    def printerate(){ 
     i.foreach {x => x.printSelf() } 
    } 
    def printerate(os:OutputStream){ 
     i.foreach { x => x.printSelf(os) } 
    } 
    } 
} 

import conversion.Convert._ 

第二個文件:

package test { 
    object program extends App { 
    new testObj(10) test 
    } 
    class testObj(i: Integer) { 
    def test(){ 
     val range = 0.until(i) 
     0.until(i).printerate() 
    } 
    } 
}