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

为什么scala不能在部分方法中推断类型?

发布时间:2020-12-16 21:33:44 所属栏目:安全 来源:网络整理
导读:看这个例子: def hello(a:String,b:String) = println(a + ":" + b)val m1 = hello("aaa",_ )m1("bbb") 它不能被编译,我需要添加类型到partial方法: val m1 = hello("aaa",_: String) 为什么Scala不知道方法的第二个参数hello是String? 解决方法 Scala的
看这个例子:

def hello(a:String,b:String) = println(a + ":" + b)
val m1 = hello("aaa",_ )
m1("bbb")

它不能被编译,我需要添加类型到partial方法:

val m1 = hello("aaa",_: String)

为什么Scala不知道方法的第二个参数hello是String?

解决方法

Scala的类型推断是基于流的.方法和函数需要显式参数类型,用于推断其他类型.不能从方法或函数体推断参数类型.然而,有时,参数类型是从外部上下文中知道的,然后不必被标记.两个例子,

val f: String => Unit = hello("aaa",_)
val s = Seq(1,2).map(_+1) // Seq[Int].map expects a function of Int argument type

以下是Martin Odersky关于Scala类型推理与ML和Haskell相比的限制的引用.挑战包括Scala的超载,记录选择和子类型化,以及需要保持简单,

The reason Scala does not have Hindley/Milner type inference is that
it is very difficult to combine with features such as overloading (the
ad-hoc variant,not type classes),record selection,and subtyping.
I’m not saying impossible — there exist a number of extensions that
incorporate these features; in fact I have been guitly of some of them
myself. I’m just saying it’s very difficult to make this work well in
practice,where one needs to have small type expressions,and good
error messages. It’s not a shut case either — many researchers are
working on pushing the boundaries here (look for instance at Remy’s
MLF). But right now it is a tradeoff of better type inferencing vs
better support for these features. You can make the tradeoff both
ways. The fact that we wanted to integrate with Java tipped the scales
in favor of subtyping and away from Hindley/Milner.

资料来源:评论在帖子Universal Type Inference is a Bad Thing.

(编辑:李大同)

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

    推荐文章
      热点阅读