2

I am new to Scala. Please tell the difference between

    def fun( t: Int => Int):Unit = {

and

    def fun(t: =>Int):Unit {

and

    def fun(t:=>Int):Unit { (without space b/w ":" and "=>"))
Surbhi Jain
  • 369
  • 1
  • 11

1 Answers1

4

def fun( t: Int => Int):Unit is a method that takes a single argument, t. Its type, Int => Int, is a function that takes an Int, and returns an Int. However, the return type of fun is Unit.

def fun(t: =>Int):Unit is a method that accepts a call by name argument t. Again, this method's return type is Unit.

See What is "Call By Name"? too.

There's no difference between the second and third methods.

Community
  • 1
  • 1
Kevin Meredith
  • 41,036
  • 63
  • 209
  • 384
  • Thanks for the answer. but is "def fun( t: Int => Int):Unit" also call by name? – Surbhi Jain Oct 19 '16 at 15:09
  • 1
    No since `=>` prefixes a call by name argument. It does not in the case you mentioned. – Kevin Meredith Oct 19 '16 at 15:27
  • I am sorry but can you elaborate. When I ran the code with def fun( t: Int => Int):Unit and passed a function in fun, that function was called only when I used the variable "t". So, isnt it call by name? – Surbhi Jain Oct 19 '16 at 16:25
  • Well, you **applied** an `Int` to `Int => Int` in order to call that function. However, in the call by name example, i.e. `def fun(t: => Int)`, `t` becomes evaluated only when it's called and every time it's called. Example: `def fun(t: => Int): Int = t + t`, and calling it: `fun( {println("calling fun"); 42} )` to observe that `calling fun` will print out twice, and `84` will be returned. – Kevin Meredith Oct 19 '16 at 16:32