加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

为什么scala不能推断部分应用中省略参数的类型?

发布时间:2020-12-16 18:48:19 所属栏目:安全 来源:网络整理
导读:考虑一下: scala def sum(x:Int,y:Int) = x+ysum: (x: Int,y: Int)Intscala sum(1,_:String)console:9: error: type mismatch; found : String required: Int sum(1,_:String) 显然Scala非常清楚_(_,_)中_的确切类型,但你必须说sum(1,_:Int).为什么? Scal
考虑一下:

scala> def sum(x:Int,y:Int) = x+y
sum: (x: Int,y: Int)Int

scala> sum(1,_:String)
<console>:9: error: type mismatch;
 found   : String
 required: Int
              sum(1,_:String)

显然Scala非常清楚_(_,_)中_的确切类型,但你必须说sum(1,_:Int).为什么?

Scala随机选择(?)选择一个:

scala> def sum(x:Int,y:String) = 1
sum: (x: Int,y: String)Int

scala> def sum(x:Int,y:Double) = 1
sum: (x: Int,y: Double)Int

scala> class Ashkan
defined class Ashkan

scala> sum(1,_:Ashkan)
<console>:10: error: type mismatch;
 found   : Ashkan
 required: Double
              sum(1,_:Ashkan)

解决方法

从这个 issue来看,听起来他们可以做到这一点,但对于一般情况来说,它相对于它所提供的好处来说太复杂了.一般情况下复杂的原因是重载方法的可能性.如果您还有:

def sum (x : Int,y : Double ) = x + y

在范围内,如果没有类型规范,你的意思是不明确的.在没有超载的情况下,类型推断可以很容易地解决,但我觉得他们觉得提供特定情况并不值得.

简而言之,听起来它是实用的,而不是理论上的限制.

我相信错误消息是通过简单地使用适当的名称和arity抓取第一个函数生成的,在非重载函数的情况下,它给人的印象是它已完全推理出类型.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读