In Scala, why can't I partially apply a function without explicitly specifying its argument types?

后端 未结 4 1549
余生分开走
余生分开走 2020-12-04 21:48

This produces an anonymous function, as you would expect (f is a function with three arguments):

f(_, _, _)

What I don\'t understand is why

4条回答
  •  温柔的废话
    2020-12-04 22:34

    If you are thinking about partial application, I thought that this was only possible with multiple parameter lists (whereas you only have one):

    def plus(x: Int)(y: Int) = x + y //x and y in different parameter lists
    
    val plus10 = plus(10) _ //_ indicates partial application
    
    println(plus10(2)) //prints 12
    

    Your example is interesting though as I was completely unaware of the syntax you describe and it appears you can have partial application with a single parameter list:

    scala> def plus2(x: Int, y: Int) = x + y
    plus2: (x: Int,y: Int)Int
    
    scala> val anon = plus2(_,_)
    anon: (Int, Int) => Int = 
    
    scala> anon(3, 4)
    res1: Int = 7
    

    So the compiler can clearly infer the type Int!

    scala> val anon2 = plus2(20,_)
    :5: error: missing parameter type for expanded function ((x$1) => plus2(20, x$1))
           val anon2 = plus2(20,_)
                                ^
    

    Hmmm, strange! I don't seem to be able to do partial application with a single parameter list. But then if I declare the type of the second parameter, I can have partial application!

    scala> val anon2 = plus2(20,_: Int)
    anon2: (Int) => Int = 
    
    scala> anon2(24)
    res2: Int = 44
    

    EDIT - one thing I would observe is that it seems like the following two shortenings are equivalent, in which case it's a bit more obvious that this is not a "partial application" but more like a "function pointer"

    val anon1 = plus2(_,_)
    val anon2 = plus2 _
    

提交回复
热议问题