问题描述
我在 Scala 中发现了几种匿名函数语法:
val m5_1 = { (n: Int) =>n * 5 }val m5_2 = (n: Int) =>{ n * 5 } :整数val m5_3: Int =>整数 = n =>{ n * 5 }
是否存在所有类型或更多语法类型?
它们都是等价的吗?
哪个更受欢迎/更不受欢迎?
如何在 m5_1
中指定返回类型?
我会尝试添加到@pamu 的回答中:
哪个更受欢迎/更不受欢迎?
我想说第二种变体有点不常见.当类型推断很容易看到时,你可以选择第一种,否则像第三种情况一样明确是好的.你不需要大括号,所以一个更简单的变体是
val m5_3: Int =>整数 = n =>n * 5
甚至
val m5_3: Int =>整数 = _ * 5
如何在 m5_1 中指定返回类型?
返回类型为 Int =>Int
,因此与您在第三种情况下使用的类型注释相同:
val m5_1: Int =>Int = { (n: Int) =>n * 5 }
当然,您可以让 Scala 使用右侧的类型推断:
val m5_1: Int =>整数 = n =>n * 5
因此这与您的第三种形式相同.
注意第二种形式的:Int
并没有定义m5_2
的类型,即Int =>Int
而不是 Int
.它只是告诉 Scala n * 5
的类型是 Int
.这可以帮助您阅读代码,但它实际上并没有改变在这种情况下推断类型的方式.你可以想象你的第二种实际存在形式:
val m5_2 = (n: Int) =>{val res = n * 5: Int//: Int 在这里是多余的,因为它已经被推断出来了资源}
其中 val res = n * 5: Int
与 val res: Int = n * 5
I have found few kinds of anonymous function syntax in scala:
val m5_1 = { (n: Int) => n * 5 }
val m5_2 = (n: Int) => { n * 5 } : Int
val m5_3: Int => Int = n => { n * 5 }
Is that all types or some more syntax kinds present?
Are they all equivalent?
Which one is more/less preferred?
How can I specify the return type in m5_1
?
I'll try to add to @pamu's answer:
I'd say the second variant is a bit uncommon. When the type inference is easily visible, you can go for the first, otherwise being explicit as in the third case is good. You don't need braces there, so a simpler variant is
val m5_3: Int => Int = n => n * 5
Or even
val m5_3: Int => Int = _ * 5
The return type is Int => Int
, so that is the same type annotation as you use in the third case:
val m5_1: Int => Int = { (n: Int) => n * 5 }
But then of course, you can let Scala use the type inference on the right hand side:
val m5_1: Int => Int = n => n * 5
And therefore this is identical to your third form.
Note that the : Int
in the second form is not defining the type of m5_2
, which is Int => Int
and not Int
. It simply tells Scala that the type of n * 5
is meant to be Int
. This can aid you reading the code, but it doesn't actually change the way the type is inferred in this case. You can think of your second form of actually being:
val m5_2 = (n: Int) => {
val res = n * 5: Int // : Int redundant here because it is already inferred
res
}
Where val res = n * 5: Int
has the same effect as val res: Int = n * 5
这篇关于Scala匿名函数语法和返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!