Why is this structural type not related as expected?

I am trying to write a simple helper method that gets something that can be closed, and some function that gets the first and ensures that the closure closes after the function is executed.

For example, I want to use it as follows:

  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:

arguments of input type [java.io.FileOutputStream] do not match the closure type of the parameter border method [T <: AnyRef {def close: Unit}]

Any ideas why?

+3
source share
2 answers

You need to write

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

There is a difference in Scala between methods with empty brackets and methods without brackets.

+11
source

. , Scala . !

class A { def f = 5 }
class B { def f() = 5 }
class C { def f()() = 5 }
def useA[X <: { def f: Int }](x: X) = x.f
def useB[X <: { def f(): Int }](x: X) = x.f
def useC[X <: { def f()(): Int}](x: X) = x.f

useA(new A)  // This works, but what other combinations do?

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

P.S. , , ,

class D extends B { override def f = 6 }
class E extends A { override def f() = 6 }

, use .

+7

Source: https://habr.com/ru/post/1787562/


All Articles