Why and how is Scala treating a tuple specially when calling a one arg function?

前端 未结 2 1698
栀梦
栀梦 2020-11-27 22:34

scala coalesces multiple function call parameters into a Tuple -- can this be disabled? discusses Scala creating a tuple to bind to one arg function. This results in

<
相关标签:
2条回答
  • 2020-11-27 23:30

    A statement, that you can omit parens when calling on-arg function is not always true. Note, that:

        println "hello"
        val puts = (s: String) => println(s)
        puts "hello"
    

    don't work either, despite that there's no tuple here. It works if you use infix notation. Following statements work great:

        Console println "hello"
        val t = (1, 2)
        Console println t
        puts apply "hello" // puts is defined above
    
    0 讨论(0)
  • 2020-11-27 23:33

    Contrary to this explanation, Scala parses println(1,2) (or Console println (1,2) for that matter) the same way it parses any two-argument method call. Later, the compiler transforms the call by wrapping the method arguments in a tuple to match the actual method type signature.

    If the compiler did not do this, perfectly valid expressions like Console println (1,2) would fail to compile because println does not take multiple arguments. There are also other valid use cases for this behavior.

    Consider an expression like foo bar (1,2) from the compiler's point of view, keeping in mind that Scala has special syntax that allows you to drop the . and the parens on method calls. This could be a call to a two-argument bar method with arguments 1 and 2, or it could be a call to a one-argument bar method with a single tuple-valued argument. The parser doesn't know anything about the bar method, so it just parses as a two-argument method call.

    During the type checking phase, suppose the compiler determines that foo has no two-argument bar method but that it does have a one-argument bar method whose signature is compatible with the tuple interpretation. Since there is no other valid interpretation, it assumes that this is what you meant and transforms the two arguments into a tuple. Note that if there is a two-argument bar method, even one that is incompatible with the actual arguments, the typer will not perform the auto-tupling transformation.

    0 讨论(0)
提交回复
热议问题