Home > other >  How to create temporary alias for a parameter to a pass by name function argument?
How to create temporary alias for a parameter to a pass by name function argument?

Time:10-27

Notice in the following code, "Hello" is printed twice in test1() but only once in test2().

Assuming I can't change change f() and g(), how can I change test2() so it behaves like test1(), whilst retaining the ability to give the expression an alias (in this case x)?

Basically I'm looking for a transformation from test1() to something like test2() that doesn't change the meaning of the code in anycase.

object Main extends App {
    println("test1")
    println(test1())
    println("test2")
    println(test2())

    def test1() : Int = {
        f(g())
    }
    
    def test2() : Int = {
        lazy val x = g()
        f(x)
    }
    
    def g() : Int = { 
        println("Hello") 
        42 
    }
    
    def f(x: => Int) : Int = {
        x * x
    }
}

CodePudding user response:

Just use def rather than val:

def test2(): Int = {
    def x = g()
    f(x)
}
  • Related