0
votes

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. Where as in version 2 it is running fine while passing type of Resource type for function : 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)}}} ^

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)}}}
}
1

1 Answers

3
votes

The first version doesn't compile because you're passing the result of getLines, which is of type Iterator[String] as the first argument. 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.

The second version works because a Source is passed as A, which fits the bound (has a matching close method)