类型参数应用于Scala函数

类型参数应用于Scala函数

问题描述:

我试图理解应用于函数的类型参数.

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

我想在下面的方法中使用泛型,但是我理解使用String和Int.

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

当我定义如下函数

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

它抱怨

 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.

感谢您的帮助.

-授予

尝试

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

编写def myfunc[Int](f:String => Int):Int时,声明类型参数Int,该参数隐藏标准类型scala.Int.这与声明def myfunc[A](f:String => A):A相同.删除返回类型时,它推断为scala.Int,即def myfunc[A](f:String => A)def myfunc[A](f:String => A):Int

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