This page is no longer maintained — Please continue to the home page at www.scala-lang.org

Fwd: by-name parameters in functions

No replies
Guilherme Silveira
Joined: 2011-05-29,
User offline. Last seen 42 years 45 weeks ago.

Just forwarding to check if there is any specific reason...

>>>

Thanks Jason,

Great, if I declare the variable, it works fine.
Btw, do you know the reason why its not acceptable to use by-name-ness
like I mentioned?

Still, it would be great if I didnt need to declare the variable as in:

class A {
 def x() = {
   val a: (=> Int) => Boolean = (i) => i>0
   a
 }
}

Is it possible to remove the variable definition and use only the type
definition within the method, something as:

class A {
 def x():((=> Int) => Boolean) = ...
}

Regards

Guilherme Silveira
Caelum | Ensino e Inovação
http://www.caelum.com.br/

On Tue, Jun 14, 2011 at 4:00 PM, Jason Zaugg wrote:
> On Tue, Jun 14, 2011 at 8:21 PM, Guilherme Silveira
> wrote:
>> I wonder why its not acceptable to use by name parameters in functions.
>>
>> scala> val y = (z:( => Boolean)) => z()
>> :1: error: no by-name parameter type allowed here
>>       val y = (z:( => Boolean)) => z()
>>
>>
>> The idea was to receive a function with no-args that would be lazily
>> evaluated, and I didnt want to force the
>> developer to write "_ => ". There is probably a language restriction
>> (something else would fail) if it was supported.
>
> You can specify the by-name-ness in the expected type.
>
> scala> val a: (Boolean, => Int) => Int = (b, i) => if (b) i else 0
> a: (Boolean, => Int) => Int =
>
> scala> a(false, sys.error(""))
> res7: Int = 0
>
> scala> a(true, sys.error(""))
> java.lang.RuntimeException:
>        at scala.sys.package$.error(package.scala:27)
>
> -jason
>

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland