Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this structural type bound does not work as expected?

I'm trying to write a simple helper method that receives something that can be closed and some function which receives the former and ensures the "closeable" is closed after executing the function.

For example, I want to use it like this:

  closing(new FileOutputStream("/asda"))(_.write("asas"))

My impl is

object Helpers {

  def closing[T <: { def close }](closeable: T)(action: T => Unit): Unit =
    try action apply closeable finally closeable close

}

But when trying to compile this simple test:

object Test {

  import Helpers._

  closing(new FileOutputStream("/asda"))(_.write("asas"))

}

The compiler complains with:

inferred type arguments [java.io.FileOutputStream] do not conform to method closing's type parameter bounds [T <: AnyRef{def close: Unit}]

Any ideas why?

like image 831
Pablo Lalloni Avatar asked Dec 02 '22 03:12

Pablo Lalloni


1 Answers

You need to write

def closing[T <: { def close() }]

there is a difference in Scala between methods with empty parentheses and methods without parentheses at all.

like image 68
Debilski Avatar answered Dec 05 '22 04:12

Debilski