这三种在 Scala 中定义函数的方式的区别 [英] Differences between these three ways of defining a function in Scala

查看:27
本文介绍了这三种在 Scala 中定义函数的方式的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定三种表示相同函数的方式f(a) := a + 1:

Given three ways of expressing the same function f(a) := a + 1:

val f1 = (a:Int) => a + 1
def f2 = (a:Int) => a + 1
def f3:(Int => Int) = a => a + 1

这些定义有何不同?REPL 没有表明任何明显的差异:

How do these definitions differ? The REPL does not indicate any obvious differences:

scala> f1
res38: (Int) => Int = <function1>
scala> f2
res39: (Int) => Int = <function1>
scala> f3
res40: (Int) => Int = <function1>

推荐答案

f1 是一个接受整数并返回整数的函数.

f1 is a function that takes an integer and returns an integer.

f2 是一个零元数的方法,它返回一个函数,该函数接受一个整数并返回一个整数.(当您稍后在 REPL 中键入 f2 时,它变成了对方法 f2 的调用.)

f2 is a method with zero arity that returns a function that takes an integer and returns an integer. (When you type f2 at REPL later, it becomes a call to the method f2.)

f3f2 相同.你只是没有在那里使用类型推断.

f3 is same as f2. You're just not employing type inference there.

这篇关于这三种在 Scala 中定义函数的方式的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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