简体   繁体   English

创建部分应用的函数时键入推断

[英]Type inference when creating a partially applied function

When I do: 当我做:

def x(i: Int, i2: Int, i3: Int) = i

x(_: Int, _: Int, 3)

Why do I have to specify that the first two arguments are "Int"? 为什么我必须指定前两个参数是“Int”?

Is there a way to make the compiler infer types, so that I can type: 有没有办法让编译器推断类型,以便我可以输入:

  x(_, _, 3)

Short answer: 简短回答:

You always have to be explicit about the parameter types of anonymous functions, unless a function type is expected. 除非需要函数类型,否则您必须明确指出匿名函数的参数类型。 "Partial application" is just a syntactical sugar for creating an anonymous function. “部分应用程序”只是用于创建匿名函数的语法糖。

Long answer: 答案很长:

First, note that you don't always have to supply type arguments when partially applying x . 首先,请注意,在部分应用x时,并不总是必须提供类型参数。 Consider this example: 考虑这个例子:

def x(i: Int, i1: Int, i2: Int) = i

def g(f: (Int, Int) => Int) = f(1, 2)

// types are inferred!
g(x(_, _, 3)) // evaluates to 1

// again, types are inferred
val f: (Int, Int) => Int = x(_, _, 3)

So clearly it helps to be in a context where a (Int, Int) => Int is expected. 很明显,在预期(Int, Int) => Int的上下文中有帮助。

Second, note that you're defining an anonymous function. 其次,请注意您正在定义匿名函数。 You could write it more explicitly like this: 您可以更明确地编写它,如下所示:

(a, b) => x(a, b, 3) 

Written this way, it should be more clear that the defining context (ie, as a lone expression) sets up no expectation for the type of the anonymous function. 以这种方式编写,应该更清楚的是,定义上下文(即,作为单独的表达式)不会对匿名函数的类型产生任何期望。 In the application of g , on the other hand, g 's parameter type implies an expectation for a specific function type. 在的应用g ,在另一方面, g的参数类型意味着特定功能类型的期望。

The compiler could, in principle, infer the types of a and b from the type of x , but it does not, as specified in §6.23 of the Scala Language Specification (bold-emphasis added): 原则上,编译器可以从x的类型推断出ab的类型,但它没有,如Scala语言规范的 §6.23中所规定的那样(添加了粗体强调):

The anonymous function ( x 1 : T 1 , ..., x n : T n ) => e maps parameters x i of types T i to a result given by expression e . 匿名函数( x 1T 1 ,..., x nT n )=> e将类型T i的参数x i映射到由表达式e给出的结果。 [...] [...]

If the expected type of the anonymous function is of the form scala.FunctionN[ S 1 ,..., S n , R ], the expected type of e is R and the type T i of any of the parameters x i can be omitted, in which case T i = S i is assumed. 如果所期望的类型的匿名函数的形式scala.FunctionN的[S 1,...,S N,R],预期的类型的电子的是R和任何参数X I可以是类型T I省略,在这种情况下假设T i = S i If the expected type of the anonymous function is some other type, all formal parameter types must be explicitly given , and the expected type of e is undefined. 如果匿名函数的预期类型是其他类型,则必须显式给出所有形式参数类型 ,并且未定义e的预期类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM