Kotlin 简明教程
Kotlin - Functions
Kotlin 是一种静态类型语言,因此,函数在它中发挥着重要的作用。我们非常熟悉函数,因为我们在前面章节的示例中一直使用它们。 function 是为了执行一个特定任务而编写的一段代码块。所有现代编程语言都支持使用函数,并且它们也被称为 methods 或 subroutines 。
Kotlin is a statically typed language, hence, functions play a great role in it. We are pretty familiar with function, as we are using function throughout our examples in our last chapters. A function is a block of code which is written to perform a particular task. Functions are supported by all the modern programming languages and they are also known as methods or subroutines.
在更广泛的层面,一个函数会接受一些输入,称为 parameters ,对这些输入执行某些操作,最后返回一个值。
At a broad level, a function takes some input which is called parameters, perform certain actions on these inputs and finally returns a value.
Kotlin Built-in Functions
Kotlin 提供了许多内置函数,我们在示例中已经使用了一些内置函数。例如, print() 和 println() 是我们用来向屏幕打印输出的最常用的内置函数。
Kotlin provides a number of built-in functions, we have used a number of buil-in functions in our examples. For example print() and println() are the most commonly used built-in function which we use to print an output to the screen.
User-Defined Functions
Kotlin 允许我们使用关键字 fun 创建我们自己的函数。用户定义的函数会接受一个或多个参数,执行操作,并将该操作的结果作为值返回。
Kotlin allows us to create our own function using the keyword fun. A user defined function takes one or more parameters, perform an action and return the result of that action as a value.
Syntax
fun functionName(){
// body of function
}
一旦我们定义了一个函数,我们可以在任何需要的时候多次调用它。下面是调用 Kotlin 函数的简单语法:
Once we defined a function, we can call it any number of times whenever it is needed. Following isa simple syntax to call a Kotlin function:
functionName()
Example
下面是一个定义和调用用户定义函数的示例,它会打印简单的“Hello,World!:
Following is an example to define and call a user-defined function which will print simple "Hello, World!":
fun main(args: Array<String>) {
printHello()
}
fun printHello(){
println("Hello, World!")
}
当你运行上述 Kotlin 程序时,它将生成以下输出:
When you run the above Kotlin program, it will generate the following output:
Hello, World!
Function Parameters
用户定义函数可以接受零个或多个参数。参数是可选的,并且可以根据需要使用。例如,我们上面定义的函数没有使用任何参数。
A user-defined function can take zero or more parameters. Parameters are options and can be used based on requirement. For example, our above defined function did not make use of any paramenter.
Example
以下是编写用户定义函数的示例,该函数将添加两个给定的数字并打印它们的总和:
Following is an example to write a user-defined function which will add two given numbers and print their sum:
fun main(args: Array<String>) {
val a = 10
val b = 20
printSum(a, b)
}
fun printSum(a:Int, b:Int){
println(a + b)
}
当你运行上述 Kotlin 程序时,它将生成以下输出:
When you run the above Kotlin program, it will generate the following output:
30
Return Values
一个 kotlin 函数基于要求返回一个值。同样,返回一个值是非常可取的。
A kotlin function return a value based on requirement. Again it is very much optional to return a value.
要返回一个值,请使用 return 关键字,并在函数的圆括号后面指定返回类型。
To return a value, use the return keyword, and specify the return type after the function’s parantheses
Example
以下是编写用户定义函数的示例,该函数将添加两个给定的数字并返回它们的总和:
Following is an example to write a user-defined function which will add two given numbers and return the sum:
fun main(args: Array<String>) {
val a = 10
val b = 20
val result = sumTwo(a, b)
println( result )
}
fun sumTwo(a:Int, b:Int):Int{
val x = a + b
return x
}
当你运行上述 Kotlin 程序时,它将生成以下输出:
When you run the above Kotlin program, it will generate the following output:
30
Unit-returning Functions
如果一个函数没有返回一个有用的值,则它的返回类型为 Unit 。Unit 是仅有一个值为 Unit 的类型。
If a function does not return a useful value, its return type is Unit. Unit is a type with only one value which is Unit.
fun sumTwo(a:Int, b:Int):Unit{
val x = a + b
println( x )
}
Unit 返回类型声明也是可选的。上面的代码等效于:
The Unit return type declaration is also optional. The above code is equivalent to:
fun sumTwo(a:Int, b:Int){
val x = a + b
println( x )
}
Kotlin Recursive Function
递归函数在许多场景中很有用,比如计算某个数字的阶乘或生成斐波那契数列。Kotlin 支持递归,这意味着 Kotlin 函数可以自身调用。
Recursion functions are useful in many scenerios like calculating factorial of a number or generating fibonacci series. Kotlin supports recursion which means a Kotlin function can call itself.
Example
下面是一个 Kotlin 程序来计算数字 10 的阶乘:
Following is a Kotlin program to calculate the factorial of number 10:
fun main(args: Array<String>) {
val a = 4
val result = factorial(a)
println( result )
}
fun factorial(a:Int):Int{
val result:Int
if( a <= 1){
result = a
}else{
result = a*factorial(a-1)
}
return result
}
当你运行上述 Kotlin 程序时,它将生成以下输出:
When you run the above Kotlin program, it will generate the following output:
24
Kotlin Tail Recursion
如果一个函数调用自身是它执行的最后一个操作,那么此递归函数有资格获得 tail recursion 。
A recursive function is eligible for tail recursion if the function call to itself is the last operation it performs.
Example
下面是一个使用尾递归来计算数字 10 阶乘的 Kotlin 程序。在这里,我们需要确保乘法是在递归调用之前完成的,而不是之后。
Following is a Kotlin program to calculate the factorial of number 10 using tail recursion. Here we need to ensure that the multiplication is done before the recursive call, not after.
fun main(args: Array<String>) {
val a = 4
val result = factorial(a)
println( result )
}
fun factorial(a: Int, accum: Int = 1): Int {
val result = a * accum
return if (a <= 1) {
result
} else {
factorial(a - 1, result)
}
}
当你运行上述 Kotlin 程序时,它将生成以下输出:
When you run the above Kotlin program, it will generate the following output:
24
Higher-Order Functions
高阶函数是一种将另一个函数作为参数和/或返回函数的函数。
A higher-order function is a function that takes another function as parameter and/or returns a function.
Example
下面是一个将两个整型参数 a 和 b 作为参数并另外将另一个函数 operation 作为参数的函数:
Following is a function which takes two integer parameters, a and b and additionally, it takes another function operation as a parameter:
fun main(args: Array<String>) {
val result = calculate(4, 5, ::sum)
println( result )
}
fun sum(a: Int, b: Int) = a + b
fun calculate(a: Int, b: Int, operation:(Int, Int) -> Int): Int {
return operation(a, b)
}
当你运行上述 Kotlin 程序时,它将生成以下输出:
When you run the above Kotlin program, it will generate the following output:
9
在这里,我们调用 higher-order function ,传递两个整型值和函数参数 ::sum 。这里, :: 是 Kotlin 中按名称引用函数的符号。
Here we are calling the higher-order function passing in two integer values and the function argument ::sum. Here :: is the notation that references a function by name in Kotlin.
Example
我们再看一个函数返回另一个函数的示例。这里我们定义了一个返回函数的高阶函数。这里 (Int) → Int 表示 square 函数的参数和返回类型。
Let’s look one more example where a function returns another function. Here we defined a higher-order function that returns a function. Here (Int) → Int represents the parameters and return type of the square function.
fun main(args: Array<String>) {
val func = operation()
println( func(4) )
}
fun square(x: Int) = x * x
fun operation(): (Int) -> Int {
return ::square
}
当你运行上述 Kotlin 程序时,它将生成以下输出:
When you run the above Kotlin program, it will generate the following output:
9
Kotlin Lambda Function
Kotlin lambda 是一个没有名称且用大括号 {} 定义的函数,它可以采用零个或多个参数和函数主体。
Kotlin lambda is a function which has no name and defined with a curly braces {} which takes zero or more parameters and body of function.
函数的主体写在变量后(如果有的话),后面跟 → 运算符。
The body of function is written after variable (if any) followed by → operator.
Kotlin Inline Function
一个 inline 函数由 inline 关键字声明。使用内联函数可以提高高阶函数的性能。内联函数告诉编译器将参数和函数复制到调用站。
An inline function is declared with inline keyword. The use of inline function enhances the performance of higher order function. The inline function tells the compiler to copy parameters and functions to the call site.
Example
fun main(args: Array<String>) {
myFunction({println("Inline function parameter")})
}
inline fun myFunction(function:()-> Unit){
println("I am inline function - A")
function()
println("I am inline function - B")
}
当你运行上述 Kotlin 程序时,它将生成以下输出:
When you run the above Kotlin program, it will generate the following output:
I am inline function - A
Inline function parameter
I am inline function - B