类型参数应用于Scala函数 [英] Type parameters applied to Scala Function

查看:71
本文介绍了类型参数应用于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

这篇关于类型参数应用于Scala函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆