Daniel Wu
Daniel Wu

Reputation: 6003

functional scala: can't compile

I have OO background and tried some functional scala code as blow, but why some compile while one doesn't:

 def fun(a: Int => Int) = a(1)

  def fun1(f: => Int => Int => Int) = {
    fun { a => fun { b => f(a)(b) } }
  }

  fun1(Int=>Int=>Int)   // it compiles but what's Int=>Int=>Int? it only define type, but no param name, how it work without compile error?
  fun1(Int=>Int=>1)  
  fun1(a=>b=>a+b)
  fun1(a=>b=>Int)  // why this has compile error while other doesn't, such as fun1(Int=>Int=>1?

And please also help me to understand the first 2 calls resulted in value of 1 but the third resulted in 2.

Upvotes: 0

Views: 64

Answers (1)

Lee
Lee

Reputation: 144136

In your first two examples, Int is just the name of a parameter, so:

fun1(Int=>Int=>Int)

is the same as

fun1(a => a => a)

where the outer parameter is shadowed by the parameter to the inner function.

In your last example, since Int is not a parameter, it is taken to be Int.type, so your last example is effectively:

fun1(_ => _ => Int.type)

Since the function needs to return an Int, this does not type check since Int.type is not compatible with Int.

Upvotes: 3

Related Questions