- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
Fwd: by-name parameters in functions
Tue, 2011-06-14, 23:54
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
>