2016-09-22 48 views
0

我寫了如下代碼的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)}}} 
} 

回答

3

第一個版本不編譯,因爲要傳遞的getLines的結果,這是Iterator[String]類型爲第一個參數。該參數必須有一個def close(): Unit方法(由A <: {def close() : Unit}限定),並且Iterator[String]不具有這樣的方法。

第二個版本的作品,因爲Source作爲A通過,符合該綁定(具有相配合close方法)

+0

謝謝!我現在進來了。 –