Scala匿名函数语法和返回类型 [英] Scala anonymous function syntax and return type

查看:238
本文介绍了Scala匿名函数语法和返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在scala中发现了几种匿名函数语法:

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?

它们都相等吗?

哪个是优先选择的?

如何在m5_1中指定返回类型?

How can I specify the return type in m5_1 ?

推荐答案

我将尝试添加到@pamu的答案中:

I'll try to add to @pamu's answer:

哪个是优先选择的?

Which one is more/less preferred?

我想说第二种变体有点不常见.当类型推断很容易看到时,您可以进行第一个,否则像在第三种情况下那样显式是好的.您在那里不需要大括号,所以一个更简单的变体是

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

甚至

val m5_3: Int => Int = _ * 5

如何在m5_1中指定返回类型?

How can I specify the return type in m5_1 ?

返回类型为Int => Int,因此与在第三种情况下使用的类型注释相同:

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 }

但是,当然,您可以让Scala在右侧使用类型推断:

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.

请注意,第二种形式的: Int并未定义m5_2的类型,即Int => Int而不是Int.它只是告诉Scala n * 5的类型是Int.这可以帮助您阅读代码,但是在这种情况下,它实际上不会改变类型的推断方式.您可以想到第二种形式的实际存在:

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
}

val res = n * 5: Intval res: Int = n * 5

这篇关于Scala匿名函数语法和返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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