scala - Type inference is not happening in polymorphic function -
i have written 2 version of codes below . in 1st version , getting run time error below , not able understand why getting error while passing iterator type function : using. in version 2 running fine while passing type of resource type function : using .
error:(23, 11) inferred type arguments [iterator[string],nothing] not conform 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)}}} ^
1st version:-
/** * created pswain on 9/22/2016. */ import java.io.{ioexception, filenotfoundexception} import scala.io.source object control { def using[ <: {def close() : unit},b ] (resource : a) (f: => b) :b = { try { f(resource) } { 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)}}} }
2nd version
/** * created pswain on 9/22/2016. */ import java.io.{ioexception, filenotfoundexception} import scala.io.source object control { def using[ <: {def close() : unit},b ] (resource : a) (f: => b) :b = { try { f(resource) } { 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)}}} }
the first version doesn't compile because you're passing result of getlines
, of type iterator[string]
first argument. argument must have def close(): unit
method (as bounded a <: {def close() : unit}
), , iterator[string]
not have such method.
the second version works because source
passed a
, fits bound (has matching close
method)
Comments
Post a Comment