shridharama
shridharama

Reputation: 979

Scala: wrapper function that returns a generic type

I am trying to create a generic wrapper function that can be wrapped around any method that returns an object. Very similar to the answer in this SO question. I tried the following:

def wrapper_function[T](f: => T): T = { 
    println("Executing now");
    val ret: T = f;
    println("Execution finished"); 
    ret 
}

def multiply2( x: Int ): Int = wrapper_function {
    println("inside multiply2"); 
    return x*2
}

However, I am observing that nothing is getting executed after the function call inside the wrapper function. Specifically, "Execution finished" is not getting printed.

scala> val x = multiply2(4)
Executing now
inside multiply2
x: Int = 8

I am using scala 2.11.8

Am I doing something wrong here? This is puzzling and I would appreciate some help.

Upvotes: 0

Views: 1291

Answers (2)

shridharama
shridharama

Reputation: 979

Assaf Mendelson's answer is correct for most situations. However, it does not work in scenarios where you don't own the code of the inner function that you are wrapping, or when there is a legitimate case for using return in the inner function (see here)

For those cases, it will work by executing the inner function in a try-finally block:

def wrapper_function[T](f: => T): T = { 
   println("Executing now");
   val ret: T = try f finally {
      println("Execution finished"); 
   }
   ret 
}

Upvotes: 0

Assaf Mendelson
Assaf Mendelson

Reputation: 13001

I believe your problem is the "return" statement.

Return in scala doesn't work the same as in java. You can take a look in this answer but basically it is something of a "stack unwinding" which would cause you to return from the wrapper function.

Consider that when you do f: => T you are actually taking the block and running it. This block has a return which simply breaks from the wrapper and returns the value (as opposed to not using return in which case its result would be used for the assignment).

In general, if you are using return in scala at the end of a function or block, you are almost always doing something wrong...

Upvotes: 6

Related Questions