Writing a function that returns => T

I am trying to write a simple converter that converts java.util.Function

to scala.Function1

:

def toScalaProducer[T](f: JavaFunction0[T]) : => T  = => f()

      

Here's another option that works well:

def toScalaFunction[T](f: JavaFunction0[T]) : () => T =
  () => f.apply()

      

The problem is, I want to pass the converted function to the existing Scala API, but that API only accepts type arguments => T

, not type () => T

.

Is there a way to write a function toScalaProducer

?

+3


source to share


1 answer


() => T

is a type for a function that takes no arguments and returns something like T

=> T

is a type for a value T

that is lazily evaluated. For example:

def myFunc(t: => Int): Unit = {
   // Do something with t
}

myFunc(reallyExpensiveFunctionProducingAnInt())

      



There reallyExpensiveFunctionProducingAnInt

can be time consuming, but will be implemented only if the value T

is used myFunc

. If you just use the type Int

instead => Int

, it will be called before the input myFunc

.

For more information, see Scala's lazy arguments: How do they work?

So, if your function toScalaProducer

just executed a Java function and had a return value T

, it should work fine with the API. It will only execute when needed, so it will behave a lot like a function pass.

+6


source







All Articles