scala#使用类型参数扩展贷款模式:issue

时间:2016-04-07 11:20:51

标签: scala

尝试使用类型参数扩展贷款模式并获取下一个错误。 看起来只是一个语法错误。 我怀疑这是一个令人讨厌的限制吗?在我的情况下,必须以某种方式提供返回类型。 谢谢!

      import java.io._

     //def withPrintWriter(file: File)( op: PrintWriter => Unit) {      
     def withPrintWriter[T: Numeric](file: File)(implicit count: Numeric[T])( op: PrintWriter => Unit) {        
    import count._
    val writer = new PrintWriter(file)      
    try {           
        for(x <- 0 to count.toInt() )
        {                           
            op(writer)
        }
    } finally {
        writer.close()
    }
}


val file = new File("date.txt")

withPrintWriter[Int]( file )( 5 ){
//withPrintWriter( file ){
    writer => writer.println( new java.util.Date )  
}

错误:         c:\ Sources \ scala \ main.scala:101:错误:&#39; =&#39;预期,但&#39;(&#39;发现。         def withPrintWriter [T:Numeric](file:File)(隐式计数:数字[T])(              op:PrintWriter =&gt;单位){                                                                                ^            c:\ Sources \ scala \ main.scala:115:错误:非法启动简单表达式         val file = new File(&#34; date.txt&#34;) ^

2 个答案:

答案 0 :(得分:0)

从快速浏览一下,看起来你的方法def在身体(括号)之前缺少= ......例如def foo(a: Int): Int = { ... }

答案 1 :(得分:0)

看起来必须发布我的问题的答案:) 隐式不需要在原始代码中使用!看起来很简单......

    def withPrintWriter[T: Numeric](file: File)(count: T)( op: PrintWriter => Unit) {       
    val writer = new PrintWriter(file)      
    try {           
        for(x <- 0 to count.asInstanceOf[Int] )
        {                           
            op(writer)
        }
    } finally {
        writer.close()
    }
}


val file = new File("date.txt")
val count : Int = 5 

withPrintWriter[Int]{ file }{ count }    
{ 
    writer => writer.println( new java.util.Date ) 
}