简体   繁体   English

Scala,为什么不能下划线 function 语法推断类型?

[英]Scala, why can't underscore function syntax infer type?

I'm new to scala and I've stumbled upon some weird cases where type inference does not work as expected.我是 scala 的新手,我偶然发现了一些类型推断无法按预期工作的奇怪案例。 for example, this does not compile:例如,这不会编译:

List(1, 2, 3, 4, 5, 6)
    .map(if _ > 3 then "foo" else "bar")

the compiler explicitly states it can't infer the type of _$1 which I take to be the first parameter of the function the syntax above desugars to.编译器明确声明它无法推断 _$1 的类型,我认为它是 function 的第一个参数,上面的语法脱糖。

somewhat frustratingly, the below code compiles just fine, even with no type annotation:有点令人沮丧的是,下面的代码编译得很好,即使没有类型注释:

List(1, 2, 3, 4, 5, 6)
    .map{ n => if n > 3 then "foo" else "bar"}

clearly there's something I'm not grasping about how _ desugars.很明显,我对如何 _ desugars 不太了解。 can somebody clue me in on what's missing?有人可以告诉我缺少什么吗?

You are missing parenthesis:您缺少括号:

List(1, 2, 3, 4, 5, 6)
    .map(if (_) > 3 then "foo" else "bar")

See it working for Scala 3.看到它适用于Scala 3。

Or more "canonical" version working both for Scala 3 and Scala 2 and mentioned in Scala 2.11 spec :或更多适用于Scala 3Scala 2并在 Scala 2.11 规范中提到的“规范”版本:

placeholder syntax.占位符语法。 equivalent anonymous function等效匿名 function
_ + 1 _ + 1 x => x + 1 x => x + 1
_ * _ _ * _ (x1, x2) => x1 * x2 (x1, x2) => x1 * x2
(_: Int) * 2 (_: 整数) * 2 (x: Int) => (x: Int) * 2 (x: Int) => (x: Int) * 2
if (_) x else y如果 (_) x 否则 y z => if (z) x else y z => if (z) x else y
_.map(f) _.map(f) x => x.map(f) x => x.map(f)
_.map( _ + 1) _.map(_ + 1) x => x.map(y => y + 1) x => x.map(y => y + 1)
List(1, 2, 3, 4, 5, 6)
  .map(_ > 3)
  .map(if (_) "foo" else "bar")

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

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