gpt4 book ai didi

scala - 高阶函数定义中的括号错误(Scala)

转载 作者:行者123 更新时间:2023-12-02 10:43:56 26 4
gpt4 key购买 nike

我在高阶定义中遇到圆括号错误。以下代码工作正常:

val foo: Int => (Int => Int) = n => n + _*2

但是,添加括号后会出现编译器错误
val foo1: Int => (Int => Int) = n => n + (_*2)

Error:(34, 56) missing parameter type for expanded function ((<x$5: error>) => x$5.$times(2))

我知道我可以使用另一种样式来避免错误:
val bar = (x: Int) => (y: Int) => x + (y*2)

我感兴趣的是括号的问题是什么以及如何以相同的格式正确使用它们来格式化高阶函数

最佳答案

匿名函数占位符参数的第一种情况

val foo: Int => (Int => Int) = 
n => n + _ * 2

扩展到
val foo: Int => (Int => Int) =
(x: Int) => (n: Int) => n + x * 2

而第二个
val foo1: Int => (Int => Int) = 
n => n + (_ * 2)

扩展到
val foo1: Int => (Int => Int) = 
n => n + (x => x * 2)

这是一个语法错误。关键是了解 scope of underscore :

If the underscore is inside an expression delimited by () or {}, the innermost such delimiter that contains the underscore will be used;

关于scala - 高阶函数定义中的括号错误(Scala),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61492116/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com