不带参数的函数,以单位作为 Scala 中的参数 [英] Functions without arguments, with unit as argument in scala

查看:30
本文介绍了不带参数的函数,以单位作为 Scala 中的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

def foo(x: Int, f: Unit => Int) = println(f())

foo(2, { Unit => 3 + 4 })

// case 1
def loop: Int = 7
foo(2, loop) // does not compile

changing loop to 
// case 2
def loop(): Int = 7
foo(2, loop) // does not compile

changing loop to
// case 3
def loop(x: Unit): Int = 7 // changing according to Don's Comments
foo(2, loop) // compiles and works fine

case 1case 2 不应该也能用吗?为什么他们不工作?

Shouldn't case 1 and case 2 also work? Why are they not working?

定义 foo 为

def foo(x: Int, y: () => Int)

然后 case 2 有效,但 case 1 无效.

then case 2 works but not case 1.

它们是否都应该工作,以任何一种方式定义函数?

Arent they all supposed to work, defining the functions either way?

我也认为 () =>foo 中的 int 是一种糟糕的风格,y:=>Int 不起作用.评论?

Also I think () => Int in foo is a bad style, y:=> Int does not work. Comments?

推荐答案

Scala 区分以下几点:

Scala distinguishes between the following things:

  • 无参数列表的函数/方法(如果是函数,则为按名称参数")
  • 具有一个空参数列表的函数
  • 具有一个单元类型参数的函数
  • Functions/methods with no parameter lists ("by-name parameter" if a function)
  • Functions with one empty parameter list
  • Functions with one parameter of type Unit

这些都不是等价的,尽管为方便起见,Scala 允许您省略空参数列表.(顺便说一句,两个空参数列表也不一样.)

None of these are equivalent, although as a convenience Scala allows you to elide empty parameter lists. (Incidentally, two empty parameter lists are also not the same.)

所以,即使 Unit 写成 (),这与函数参数 parens ()< 相同/code> 用于函数或方法.相反,将 () 视为 Tuple0.

So, even though Unit is written (), this is not the same as the function argument parens () for a function or method. Instead, think of () as a Tuple0.

所以,如果你说 f: Unit =>int,你的意思是f接受一个参数,但它是一个非常无聊的参数,因为它是Unit,它必须始终是同一个无聊的Tuple0()".你正在写的是 f: (Unit) => 的缩写.Int.

So, if you say f: Unit => Int, what you mean is "f takes one parameter, but it's a really boring parameter because it is Unit, which must always be the same boring Tuple0 value ()". What you're writing is really short for f: (Unit) => Int.

如果你说 f: () =>Int,那么你的意思是f 不接受任何参数并产生一个 Int".

If you say f: () => Int, then you mean that "f takes no parameters and produces an Int".

如果你说 f: =>Int,那么您的意思是延迟执行任何生成 Int 值的语句,直到我们在此代码中使用它(并每次重新评估它)".从功能上讲,这最终与 f: () =>; 基本相同.Int(并且在内部被转换为相同的 Function0 类),但它有不同的用法,大概是为了允许更紧凑的闭包形式(你总是省略 => 在调用代码中).

If you say f: => Int, then you mean that "delay the execution of whatever statement produces an Int value until we use it in this code (and re-evaluate it each time)". Functionally, this ends up being basically the same as f: () => Int (and internally is converted into the same Function0 class), but it has a different usage, presumably to allow for a more compact form of closures (you always omit the => in the calling code).

这篇关于不带参数的函数,以单位作为 Scala 中的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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