I would like to create a function with the following signature:
def myFunction[T](functionWithName: (String, => T)): T
so that I can call it, e.g., like this: val x = myFunction("abc" -> 4 * 3)
. Tuple doesn't accept by-name parameter, however, so the signature above is invalid.
Inspired by this answer, I tried the following implicit conversion:
implicit class ByName[T](getValue: => T) extends Proxy {
def apply(): T = getValue
def self = apply()
}
def myFunction[T](functionWithName: (String, ByName[T])): T = {
// do something
functionWithName._2()
}
The implicit doesn't work in this case, however (unlike in the linked answer).
- Why does the implicit conversion to
ByName
doesn't work? - How can I achieve the desired effect of calling
myFunction("abc" -> 4 * 3)
where4 * 3
is passed by name?