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()
}
}
}
我接近此類型轉換的方式有什麼問題?
作爲一個樣式注意,可以考慮使用隱式類,而不是對象,具有隱含DEFS:HTTP://docs.scala- lang.org/overviews/core/implicit-classes.html。 – Gal