scala type inference with _ place holder

后端 未结 2 416
傲寒
傲寒 2021-01-18 04:40
List(\"This\",\"is\",\"Scala\").foreach(a => print(a+\" \"))

compiles fine, but

List(\"This\",\"is\",\"Scala\").foreach(print(_+         


        
2条回答
  •  逝去的感伤
    2021-01-18 05:25

    The problem is that this

    List("This","is","Scala").foreach(print(_+" "))
    

    is not equivalent to

    List("This","is","Scala").foreach(a => print(a+" "))
    

    but to

    List("This","is","Scala").foreach(print(a => a+" "))
    

    Now, let's see the type signature of foreach:

    def foreach [B] (f: (A) ⇒ B) : Unit
    

    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].

    In a => print(a+" ") the type of a is already known then: String.

    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
    

    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.

提交回复
热议问题