_占位符的scala类型推断 [英] scala type inference with _ place holder
问题描述
List("This","is","Scala").foreach(a => print(a+" "))
编译正常,但是
List("This","is","Scala").foreach(print(_+" "))
无法抱怨缺少参数类型.我不知道为什么它会失败.
fails complaining of missing parameter type. I couldn't figure out why it fails.
我的意思是打印而不是println-并不是说它在逻辑上有所不同.
I meant print not println - not that it makes logical difference.
推荐答案
问题是这个
List("This","is","Scala").foreach(print(_+" "))
不等同于
List("This","is","Scala").foreach(a => print(a+" "))
但要
List("This","is","Scala").foreach(print(a => a+" "))
现在,让我们来看一下foreach
的类型签名:
Now, let's see the type signature of foreach
:
def foreach [B] (f: (A) ⇒ B) : Unit
其中,A
是List
本身的类型参数.由于我们有一个List[String]
,因此编译器知道必须将Function[String, B]
传递给foreach
.
where A
is the type parameter of the List
itself. Since we have a List[String]
, the compiler knows one has to pass to foreach
a Function[String, B]
.
在a => print(a+" ")
中,a
的类型是已知的,然后:String
.
In a => print(a+" ")
the type of a
is already known then: String
.
在print(a => a+" ")
中存在问题,因为print
不是Function
.但是,编译器尚未考虑-仍在尝试编译a => a+" "
.因此,让我们来看一下Predef.print
的类型:
In print(a => a+" ")
there is a problem, as print
is not a Function
. However, the compiler hasn't considered that yet -- it's still trying to compile a => a+" "
. So let's look at the type of Predef.print
:
def print (x: Any) : Unit
因此,a => a+" "
必须是Any
类型,这当然意味着它可以是任何东西.它并没有帮助编译器断言a
的类型是什么.其实并不重要,因为您不想首先打印Function
.
So a => a+" "
must be of type Any
, which, of course, means it can be anything. It doesn't help the compiler in asserting what the type of a
is. Which doesn't really matter, because you didn't want to print a Function
in first place.
这篇关于_占位符的scala类型推断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!