[英]Type inference is not happening in polymorphic function
I have written 2 version of codes as below . 我已经编写了以下两个版本的代码。 In 1st version , I am getting run time error as below , not able to understand why i am getting error while I am passing Iterator type for function : using . 在第一个版本中,我收到如下的运行时错误,无法理解为函数传递Iterator类型时为什么出错: using 。 Where as in version 2 it is running fine while passing type of Resource type for function : using . 在版本2中,当传递函数的Resource类型的类型时,它运行良好: using 。
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)}}} ^ 错误:(23,11)推断的类型参数[Iterator [String],Nothing]不符合使用类型参数界限的方法[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 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)}}}
}
2nd version 第二版
/**
* 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)}}}
}
The first version doesn't compile because you're passing the result of getLines
, which is of type Iterator[String]
as the first argument. 第一个版本无法编译,因为您要传递getLines
的结果,该结果的类型为Iterator[String]
作为第一个参数。 That argument must have a def close(): Unit
method (as bounded by A <: {def close() : Unit}
), and Iterator[String]
does not have such a method. 该参数必须具有def close(): Unit
方法(由A <: {def close() : Unit}
),而Iterator[String]
没有这种方法。
The second version works because a Source
is passed as A
, which fits the bound (has a matching close
method) 第二个版本有效,因为Source
作为A
传递,它适合边界(具有匹配的close
方法)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.