“代码:="是什么意思?单位"在 Scala 中是什么意思? [英] What does "code: => Unit" mean in scala?
问题描述
有谁知道 Scala 中 => 单位的类型?我不知道 => Unit 的含义以及如何使用它.我定义了一个如下所示的函数:
Does anyone know the type of => Unit in scala? I don't know the meaning of => Unit and how to use it. I defined a function like below:
def test(code: => Unit){
print("start ...")
code
print("end ....")
}
test(print(1))
这是否意味着带有返回 Unit 的任何参数的函数?
Does it means a function with any arguments returning Unit?
谢谢
推荐答案
这种参数被称为by-name参数
<代码>=>B 表示返回一个 B
值的代码块 a,它们的目的是仅在您调用参数时才对它们进行评估.
=> B
represents a block a of code which return a B
value, their purpose is that they are evaluated only when you call the parameter.
def foo(code: => Int) {
println("Not yet evaluated")
val result = code
println("parameter evaluated %s, is it an int ? %s " format (
result, result.isInstanceOf[Int]) )
}
您可以通过以下方式调用 foo
:
And you can call foo
in the following way :
foo(1)
或
val a = 3
val b = 5
foo {
val c = a * a
c * b
}
另一种传递参数的方式是按值:参数在被发送到方法之前被评估
The other style of passing parameter is by-value : parameters are evaluated before they are sent to the method
def foo(code : Int) {
println("Parameter already evaluated")
val result = code
println("parameter evaluated : " + result)
}
参考资料
这篇关于“代码:="是什么意思?单位"在 Scala 中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!