在 Scala 中,为什么我不能在没有明确指定参数类型的情况下部分应用函数? [英] In Scala, why can't I partially apply a function without explicitly specifying its argument types?

查看:26
本文介绍了在 Scala 中,为什么我不能在没有明确指定参数类型的情况下部分应用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这会产生一个匿名函数,正如您所期望的(f 是一个带有三个参数的函数):

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

f(_, _, _)

我不明白的是为什么这不能编译,而是给出缺少参数类型"错误:

What I don't understand is why this doesn't compile, instead giving a "missing parameter type" error:

f(_, _, 27)

相反,我需要明确指定下划线的类型.鉴于 Scala 知道函数 f 的参数类型是什么,它难道不应该能够推断出它们吗?

Instead, I need to specify the types of the underscores explicitly. Shouldn't Scala be able to infer them given that it knows what the function f's parameter types are?

推荐答案

以下参考是 Scala 语言规范

考虑以下方法:

def foo(a: Int, b: Int) = 0

Eta Expansion 可以将其转换为 (Int, Int) => 类型的值.整数.在以下情况下调用此扩展:

Eta Expansion can convert this to a value of type (Int, Int) => Int. This expansion is invoked if:

a) _ 用于代替参数列表(方法值(第 6.7 节))

a) _ is used in place of the argument list (Method Value (§6.7))

val f = foo _

b) 参数列表被省略,表达式的预期类型是函数类型(第 6.25.2 节):

b) the argument list is omitted, and expected type of expression is a function type (§6.25.2):

val f: (Int, Int) => Int = foo

c) 每个参数都是 _ (a 特殊情况匿名函数的占位符语法"(第 6.23 节)

c) each of the arguments is _ (a special case of the 'Placeholder Syntax for Anonymous Functions' (§6.23))

val f = foo(_, _)   

表达式,foo(_, 1) 不符合 Eta 扩展的条件;它只是扩展为 (a) =>foo(a, 1)(第 6.23 节).常规类型推断不会试图找出 a: Int.

The expression, foo(_, 1) doesn't qualify for Eta Expansion; it just expands to (a) => foo(a, 1) (§6.23). Regular type inference doesn't attempt to figure out that a: Int.

这篇关于在 Scala 中,为什么我不能在没有明确指定参数类型的情况下部分应用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆