This is the 29th day of my participation in Gwen Challenge
I have seen many interesting topics about Kotlin on portal.kotlin-academy.com/#/ recently. Personally, I think it is very suitable for Kotlin lovers, interested partners can consult by themselves. The interesting Kotlin series records their understanding of each question.
0 x01: Scala – like functions provides
fun hello(a) = {
println("Hello, World")}fun main(args: Array<String>) {
hello()
}
Copy the code
What is the result of the above code? Optional:
- Does not compile
- Prints “Hello, World”
- Nothing
- Something else
Think about it and write down the answer in your mind.
Analysis of the
Hello () = hello();
fun hello(a) = {
println("Hello, World")}Copy the code
And our common function is written like this:
fun hello(a) {
println("Hello, World")}Copy the code
We have an extra = sign, which makes the two functions fundamentally different. Let’s take a look at some common ways to write without an equal sign:
fun hello(a) {
println("Hello, World")}Copy the code
- Function name: hello
- Function parameters: None
- Return value: Unit
Let’s look at the equal sign.
fun hello(a) = {
println("Hello, World")}Copy the code
- Function name: hello
- Function parameters: None
- Return value:???
What is the return type of this function? Let’s start with an example:
fun isPositive(number: Int) = number > 0
Copy the code
Number > 0 is an expression. The return value Boolean is omitted because the return type can be inferred from the expression.
In contrast to the hello function above, it is also a shorthand that omits the return value type. So let’s look at the equals sign
= {
println("Hello, World")}Copy the code
Lambda expressions are a way of instantiating function types, so the return value of hello is a function of type () →\rightarrow→ Unit. So the answer is pretty obvious. After we complete the return type, the title content becomes:
fun hello(a): () - >Unit = {
println("Hello, World")}fun main(args: Array<String>) {
hello()
}
Copy the code
Calling hello from main only returns an instance of the function type, but does not call it, so “hello, World” is not printed. The correct answer is: 3.
What if we wanted to print “Hello, World”? Three ways:
- One: get rid of it
hello
An equal sign in a function definition
fun hello(a) { println("Hello, World")}fun main(args: Array<String>) { hello()}
Copy the code
- Second: through the operator
(a)
Invoke an instance of a function type
fun hello(a) = { println("Hello, World")}fun main(args: Array<String>) { hello()()}
Copy the code
- The third way: through the operator
invoke
Invoke an instance of a function type
fun hello(a) = { println("Hello, World")}fun main(args: Array<String>) { hello().invoke()}
Copy the code