0

1 def nonStrict[A](a: () => A) = a

2 def nonStrict[A](a: => A) = a

I'm reading the red scala book which presents => A as 'nicer syntax' for () => A

but 1 and 2 are apparently not equivalent

scala> def nonStrict[A](a: => A) = a
def nonStrict[A](a: => A): A

scala> nonStrict[Int](1)
val res13: Int = 1

scala> def nonStrict[A](a: () => A) = a
def nonStrict[A](a: () => A): () => A

scala> nonStrict[Int](() => 1)
val res14: () => Int = $Lambda$1325/0x000000080110ea58@35af404f

scala> nonStrict[Int](1)
                      ^
       error: type mismatch;
        found   : Int(1)
        required: () => Int 

i would like to be able to think of => A as an abbreviation of () => A where call-by-name arguments are just functions with no arguments, which we explicitly call when we want to evaluate them.

so what's going on? is it that if you define a function f(a: => A) calling the function f(aa) where aa: A actually makes a () => aa and calling aa actually evaluates this function, which makes it look like calling the parameter a: => A just delays evaluation to give you A?

edit as question was deleted: I'm looking for an answer to how => A is implemented rather than just the difference between => A and () => A

A.Lee
  • 1
  • 2
  • 1
    @toyotaSupra: code and error message are in text in this question – Mat Sep 06 '22 at 12:41
  • 3
    The difference is that `=> A` not only has nicer syntax on call site, but inside the method body as well _(although I personally don't call it nicer in that regard)_, thus just doing `a` is enough to evaluate the _"function"_ - Note that in reality `=> A` is actually its own type which is confusing and overcomplicated IMHO, but the language creators disagree with me in that regard: https://contributors.scala-lang.org/t/make-by-name-parameters-just-sugar-syntax-rather-than-actual-types/5228 – Luis Miguel Mejía Suárez Sep 06 '22 at 13:21
  • @LuisMiguelMejíaSuárez Thanks, that's gets me a bit closer to what I'm looking for. So at the moment is `=> A` actually implemented as a `Function0` value under the hood? – A.Lee Sep 06 '22 at 21:33
  • @A.Lee I am not sure about the actual implementation, it probably is or maybe something different but very similar, no idea. What I can tell you is that they are evaluated when referenced and that they are their own type. – Luis Miguel Mejía Suárez Sep 07 '22 at 00:19

0 Answers0