繁体   English   中英

具有类型参数的类的Scala隐式类型转换

[英]Scala Implicit Type Conversion of Classes with Type Parameters

我正在尝试向scala.collection.Iterable特质添加功能,更具体地说,是一个遍历元素并将其打印输出(如果没有参数的话,输出到控制台,否则输出到输出流参数)的printerate函数。 我正在使用为对象printSelf()创建的预定义扩展方法。 但是,这导致了编译器错误,“值printSelf不是类型参数Object的成员。” 我还希望将其作为一个单独的文件,以便在多个项目和应用程序之间轻松使用。

这是我当前的转换文件代码:

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) }
    }
  }
}

我也在尝试进行测试的代码中收到类似的错误,“ value 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()
    }
  }
}

我进行这种类型转换的方式有什么问题?

实际上有几件事:

  1. Convert应该是一个对象,而不是一个类。
  2. 您使用对象而不是任何
  3. 您将Object用作通用类型标识符,而不是将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()
    }
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM