我寫了如下代碼的2版本。在第一個版本中,我得到如下的運行時錯誤,不能理解爲什麼我在傳遞Iterator類型函數時出現錯誤:使用。在版本2中,它在傳遞函數的資源類型類型時運行良好:使用。類型推斷沒有發生在多態函數中
Error:(23, 11) inferred type arguments [Iterator[String],Nothing] do not conform to method using's type parameter bounds [A <: AnyRef{def close(): Unit},B] control.using(Source.fromFile("C:\Users\pswain\IdeaProjects\test1\src\main\resources\employee").getLines){a => {for (line <- a) { println(line)}}} ^
1版: -
/**
* Created by PSwain on 9/22/2016.
*/
import java.io.{IOException, FileNotFoundException}
import scala.io.Source
object control {
def using[ A <: {def close() : Unit},B ] (resource : A) (f: A => B) :B =
{
try {
f(resource)
} finally {
resource.close()
}
}
}
object fileHandling extends App {
control.using(Source.fromFile("C:\\Users\\pswain\\IdeaProjects\\test1\\src\\main\\resources\\employee").getLines){a => {for (line <- a) { println(line)}}}
}
第二版
/**
* Created by PSwain on 9/22/2016.
*/
import java.io.{IOException, FileNotFoundException}
import scala.io.Source
object control {
def using[ A <: {def close() : Unit},B ] (resource : A) (f: A => B) :B =
{
try {
f(resource)
} finally {
resource.close()
}
}
}
object fileHandling extends App {
control.using(Source.fromFile("C:\\Users\\pswain\\IdeaProjects\\test1\\src\\main\\resources\\employee")){a => {for (line <- a.getLines) { println(line)}}}
}
謝謝!我現在進來了。 –