scala - Can we have an array of by-name-parameter functions? -
in scala have by-name-parameters can write
def foo[t](f: => t):t = {    f // invokes f     } // use as: foo(println("hello")) i want same array of methods, want use them as:
def foo[t](f:array[ => t]):t = {     // not work    f(0) // invokes f(0)              // not work } foo(println("hi"), println("hello")) // not work is there way want? best have come is:
def foo[t](f:() => t *):t = {    f(0)() // invokes f(0)     } // use as: foo(() => println("hi"), () => println("hello")) or
def foo[t](f:array[() => t]):t = {     f(0)() // invokes f(0)     } // use as:  foo(array(() => println("hi"), () => println("hello"))) edit: proposed sip-24 not useful pointed out seth tisue in comment this answer.
an example problematic following code of utility function trycatch:
type unittot[t] = ()=>t def trycatch[t](list:unittot[t] *):t = list.size match {   case if > 1 =>      try list.head()     catch { case t:any => trycatch(list.tail: _*) }   case 1 => list(0)()   case _ => throw new exception("call list must non-empty") } here trycatch takes list of methods of type ()=>t , applies each element successively until succeeds or end reached. 
now suppose have 2 methods:
def getyahoorate(currencya:string, currencyb:string):double = ??? and
def getgooglerate(currencya:string, currencyb:string):double = ??? that convert 1 unit of currencya currencyb , output double. 
i use trycatch as:
val usdeurorate = trycatch(() => getyahoorate("usd", "eur"),                             () => getgooglerate("usd", "eur")) i have preferred:
val usdeurorate = trycatch(getyahoorate("usd", "eur"),                             getgooglerate("usd", "eur")) // not work in example above, getgooglerate("usd", "eur") invoked if getyahoorate("usd", "eur") throws exception. not intended behavior of sip-24.
as of scala 2.11.7, answer no.  however, there sip-24, in future version f: => t* version may possible.
Comments
Post a Comment