2

anybody can give me explain how to work call-by-name inside of the scala compiler? Syntactic shortcut for that method will be such: arg: =>Int will be transformed to arg: () => Int and captures the passed parameter to the function, how a closure? i.e real type of call-by-name parameter such: Function0[_]?

Thanks.

dvigal
  • 165
  • 1
  • 1
  • 10
  • 1
    What do you want to do? The question isn't clear. – Daniel C. Sobral Feb 07 '12 at 17:59
  • @DanielC.Sobral Hi. Let's assume that i want something like such: `def foo(i: =>Int): Either[Int,Function1[here need the type of 'call-by-name' parameter,Either[_,_]]]`. **How can i write it?** The question of purely hypothetical... – dvigal Feb 07 '12 at 18:38

3 Answers3

4

Call-by-name parameters, as you yourself have discovered, desugar down to Function0[A]. They do not have a first class support, and thus no different type as such.

You can kind of achieve something along those lines using Name from Scalaz. For that, see the accepted answer here.

Community
  • 1
  • 1
missingfaktor
  • 90,905
  • 62
  • 285
  • 365
3

If I understand the question correctly, yes the syntax => Int is essentially a lightweight syntax for anonymous parameterless function () => Int, that is represented by type Function0[Int] in Scala. Furthermore, within the VM by-name parameters translate to inner classes.

elk
  • 442
  • 3
  • 7
1

A by-name parameter's type is parameterless method (see @som-snytt's comment). It cannot be used on Scala 2.x anywhere except on a method's parameter type.

You can use a Function0 in place of a parameter that is being passed by-name, but that has different semantics.

Daniel C. Sobral
  • 295,120
  • 86
  • 501
  • 681
  • 1
    It is a "method type", per spec. – som-snytt Feb 27 '20 at 18:59
  • @som-snytt I wonder if that's a new thing. I'm pretty sure I spent a long time with the spec back in 2012, and "by name" was not considered a type a the time. Do you have a reference in the spec? – Daniel C. Sobral Mar 23 '20 at 16:03
  • I had issues with both by-name and repeated params, esp around overloading. Method type is https://scala-lang.org/files/archive/spec/2.13/03-types.html#method-types and by-name https://scala-lang.org/files/archive/spec/2.13/04-basic-declarations-and-definitions.html#by-name-parameters says plainly it is a "parameterless method type". Sorry to resurrect an old answer; your words carry special weight. The other response also treats it as mere sugar. I wonder if 2.8 or 2.9 was in use. – som-snytt Mar 23 '20 at 20:25
  • @som-snytt I wouldn't have been surprised if it had been 2.7! I'm guessing 2.8, though it seems 2.9 was already around? I'm not sure the spec was updated, though. The wording of the special case on the method type does look rather unfamiliar to me. It does seem to be something added afterwards, but, hey, I might just have been wrong. – Daniel C. Sobral Mar 26 '20 at 01:13