One argument referencing another in the argument list

65 views Asked by At

Occasionally, I encounter one argument wanting to reference another. For instance,

def monitor(time: Double, f: Double => Double, resolution: Double = time / 10) = {...}

Note that resolution refers to time. Are there languages where this is possible? Is it possible in Scala?

2

There are 2 answers

0
volia17 On BEST ANSWER

I don't know any langage where this construction is possible, but a simple workaround is not difficult to find.

In scala, something like this is possible :

scala> def f(i : Int, j : Option[Int] = None) : Int = {
     | val k = j.getOrElse(i * 2)
     | i + k
     | }
f: (i: Int, j: Option[Int])Int

scala> f(1)
res0: Int = 3

scala> f(1, Some(2))
res1: Int = 3

In scala, you can also make something like this :

scala> def g(i : Int)(j : Int = i * 2) = i + j
g: (i: Int)(j: Int)Int

scala> g(2)(5)
res6: Int = 7

scala> g(2)()
res7: Int = 6
0
Michael Zajac On

It is somewhat possible in Scala, but you have to curry the parameters:

def monitor(time: Double, f: Double => Double)(resolution: Double = time / 10) 

You cannot do it in the way the question is posed.