al249
al249

Reputation: 1

Scala call-by-name arguments: Equivalent to functions with no arguments? Or not..?

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

Upvotes: 0

Views: 49

Answers (0)

Related Questions