Kotlin函数声明:在大括号之前等号 [英] Kotlin function declaration: equals sign before curly braces
问题描述
-
没有
=
sign:fun foo(){
bar()
println(baz)
}
通过调用
foo()$ c
$ li $=
签名:fun foo()= {
bar()
println(baz)
}
在这里,当调用
foo()
时,什么都不会发生,执行一个可以写foo()()
。
这两个声明和声明的区别是什么?为什么它们的行为不同?
这个问题虽然没有多大意义,但是由作者故意询问和回答,因为有些问题已经发布在人们由于错误而出现问题的地方函数定义
尽管视觉相似,但这两个声明的概念完全不同。
-
不带等号的函数声明是
单元
- 返回函数(类似于Java的void
功能)。
大括号里面的内容是它的正文,它在函数调用中被正确执行。该函数可以用
Unit
明确指定:
$ bfun foo( ):单位{
bar()
println(baz)
返回单位
}
对于
Unit
- 返回函数,Kotlin不要求返回语句和显式返回类型,并且通常都省略它们。 -
带等号的函数声明是单表达式函数,它所做的只是返回等号右边的内容。
一个更简单的例子:
fun getInt()= 1
只是fun的一个简短形式getInt():Int {return 1}
。
在
foo
中,表达式为一个lambda ,它是onl y返回,未执行。 $ b $ <返回类型foo
是() - >单元
,一个函数本身,因此foo
是一个 higher-order function 。
没有语法糖和显式类型,
foo
可以改写为
fun foo():() - > Unit {
val result:() - >单位= {bar(); println(baz)}
返回结果
}
至于用法,
foo
返回的函数可以存储在一个变量中,传递给以后可以调用:val f = foo()
$ bf()//相当于
f.invoke()
这也是为什么
foo()()
来自拉姆达体的代码。
In Kotlin, the function declaration syntax allows you to write equals sign before the curly braces. Consider these two examples:
Without
=
sign:fun foo() { bar() println("baz") }
The code inside the body gets executed by just calling
foo()
.With
=
sign:fun foo() = { bar() println("baz") }
Here, when
foo()
is called, nothing happens, but to get the body executed one can writefoo()()
.
What is the difference in these two declarations and why do they behave differently?
This question, though having not much meaning, is intentionally asked and answered by the author, because a few questions have already been posted where people got problems because of incorrect function definitions.
Despite visual similarity, the idea of these two declarations is completely different.
Function declaration without equals sign is a
Unit
-returning function (similar to Java'svoid
functions).What's inside the curly braces is its body, which gets executed right on the function call. The function can be rewritten with
Unit
explicitly specified:fun foo(): Unit { bar() println("baz") return Unit }
Kotlin doesn't require the return statement and explicit return type for
Unit
-returning functions, and both are usually omitted.Function declaration with equals sign is a single-expression function, and what it does is just return what's to the right of equals sign.
A simpler example:
fun getInt() = 1
is just a shorter form offun getInt(): Int { return 1 }
.In
foo
, the expression is a lambda, and it is only returned, not executed.Return type of
foo
is() -> Unit
, a function itself, and thusfoo
is a higher-order function.Without the syntactic sugar and with explicit type,
foo
can be rewritten asfun foo(): () -> Unit { val result: () -> Unit = { bar(); println("baz") } return result }
As to the usage, the function which
foo
returns can be stored in a variable, passed around and can later be invoked:val f = foo() f() //equivalent to f.invoke()
This is also why
foo()()
in the example executes the code from the lambda body.
这篇关于Kotlin函数声明:在大括号之前等号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!