tags:

views:

194

answers:

4

Given this code:

def getFunc(funcName:String, param:Int) = match funcName {
  case "FooFunc" => FooFunc(param)
  [...]
}

def FooFunc(param:Int) = param + SomeObject.SomeVariable

How could I return FooFunc with param applied, without evaluating it? The reason I'd want to do this is because FooFunc, as you can see, relies on an external variable so I'd like to be able to call it with param already applied. What would the return type of getFunc need to be?

+1  A: 

You could add another void parameter, so the function is only evaluated when it is applied to this parameter.

Though I'd rather use a proper object instead of a function in this case.

starblue
+1  A: 

I'm sure there's many options, but you can use:

return { Unit => FooFun(param) }
GClaramunt
+4  A: 

Easy:

def getFunc(funcName: String, param: Int) = funcName match {
  case "FooFunc" => () => FooFunc(param)
  [...]
}

Your method has a good name: getFunc is supposed to return a function, so it will.

Alexander Azarov
+2  A: 

The lazyness must be defined at the call site, in Scala. You can do:

lazy val x = getFunc(...) // getFunc only gets evaluated when needed

Or you can change the signature:

def FooFunc(param:Int) = () => param + SomeObject.SomeVariable
...
val x = getFunc(...) // x contains a function from Unit into something

x() // Use x here, causing the evaluation
Daniel