Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type parameters applied to Scala Function

I am trying to understand the type parameters when applied to a function.

I would like to use Generic Types in the below method but using String and Int for my understanding.

When I define a function as below

  def myfunc[Int](f:String => Int):Int =  {
    Integer.min(1,2)
  }

it complains

 found   : scala.this.Int
 required: Int&0
      Integer.min(1,2)

However if I remove the return type of the function ( which I understand is not required), it compiles fine.

I am not able to infer why removing the return type makes the compilation successful.

Appreciate your help.

-Amit

like image 375
Amit Avatar asked Jul 21 '26 19:07

Amit


1 Answers

Try

def myfunc(f:String => Int):Int =  {
  Integer.min(1,2)
}

When you write def myfunc[Int](f:String => Int):Int you declare type parameter Int, which hides standard type scala.Int. This is the same as if you declared def myfunc[A](f:String => A):A. When you remove return type it's inferred to be scala.Int, i.e. def myfunc[A](f:String => A) is def myfunc[A](f:String => A):Int

like image 126
Dmytro Mitin Avatar answered Jul 23 '26 11:07

Dmytro Mitin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!