kotlin函数
In this tutorial, we’ll be discussing at length, Functions in Kotlin. We’ll discuss everything you need to know about kotlin functions right from the syntax to the various implementations.
在本教程中,我们将详细讨论Kotlin中的功能。 我们将从语法到各种实现,讨论您需要了解的有关kotlin函数的所有信息。
In Kotlin, functions can be used at the top level. By top level, we mean they can be defined without the need to be enclosed in a class or anywhere. This is one of the primary reasons that in Kotlin, we use the term functions instead of methods.
在Kotlin中,可以在顶层使用功能。 在顶层,我们的意思是可以定义它们而无需将其包含在类中或任何地方。 这是在Kotlin中我们使用术语函数而不是方法的主要原因之一。
Functions can be defined into various types depending on the various categories. At a very high level, we define the function in the following two categories.
可以根据各种类别将功能定义为各种类型。 在很高的层次上,我们在以下两类中定义函数。
main()
, println()
etc. defined in the standard library Kotlin标准函数 :Kotlin在标准库中定义了自己的一组函数,例如main()
, println()
等。 Functions in Kotlin are fun! No doubt a function is defined using the keyword fun
. It is followed by the function name. The parameters along with their types go inside the brackets. The return type is set outside the brackets as shown below.
Kotlin中的功能很有趣! 无疑,功能是使用关键字fun
定义的。 其后是函数名称。 参数及其类型放在方括号内。 返回类型设置在括号之外,如下所示。
fun function_name(param1: Type1, param2: Type2,.....) : SetReturnTypeHere{
//function body goes here.
}
Note: To override a function in subclasses we need to append the modifier override
注意:要覆盖在子类中的函数,我们需要追加修改override
Let us define a function that calculates the sum of two numbers. We’ll do this in each of the types defined by scope.
让我们定义一个计算两个数字之和的函数。 我们将在范围定义的每种类型中执行此操作。
fun main(args: Array) {
sumOfTwo(2,3) //returns 5
}
fun sumOfTwo(a: Int, b: Int): Int{
return a + b
}
To call the function we just need to pass the parameters as the arguments.
顶级功能要调用该函数,我们只需要传递参数作为参数即可。
fun main(args: Array) {
var a = A()
a.sumOfTwo(2,3)
}
class A {
fun sumOfTwo(a: Int, b: Int): Int{
return a + b
}
}
会员职能 fun main(args: Array) {
sumOfDoubleOfTwo(2,3) //returns 5
print(sumOfDoubleOfTwo(2,3)) //prints 10. This is a triple nested function.
}
fun sumOfDoubleOfTwo(a: Int, b: Int): Int {
fun letMeDoubleAndAdd(): Int {
return a * 2 + b * 2
}
return letMeDoubleAndAdd()
}
letMeDoubleAndAdd()
does the execution part and returns the result to the first function.
Note: The print
function in the above code implicitly encloses the sumOfDoubleOfTwo()
function. Hence the sumOfDoubleOfTwo()
acts as a nested function in the second statement.
letMeDoubleAndAdd()
执行部分并将结果返回给第一个函数。
注意 :上面代码中的print
函数隐式包含sumOfDoubleOfTwo()
函数。 因此, sumOfDoubleOfTwo()
在第二条语句中充当嵌套函数。
If there’s no return type, we can leave the return type space empty.
如果没有返回类型,我们可以将返回类型空间留空。
fun main(args: Array) {
helloWorld() //prints Fun says hello world
print(helloWorld()) //prints Fun says hello world\nkotlin.Unit
}
fun helloWorld() {
println("Fun says hello world")
}
What’s kotlin.Unit?
Unit
is the Kotlin equivalent of void
in Java.
So the above function can also be written as :
什么是kotlin.Unit?
Unit
是Java中void
的Kotlin等效项。
所以上面的函数也可以写成:
fun helloWorld() :Unit {
println("Fun says hello world")
}
We can stay away from the above definition though since setting the Unit
return type is not compulsory.
尽管由于不必设置Unit
返回类型,所以我们可以不使用上述定义。
Kotlin allows setting default values in the function definition. This way, if you don’t pass an argument in the function call, the default value would be used as shown below.
Kotlin允许在函数定义中设置默认值。 这样,如果您未在函数调用中传递参数,则将使用默认值,如下所示。
fun main(args: Array) {
print(appendAllParams("Hi", message = "How are you doing?")) //prints Hi Jay, How are you doing?
}
fun appendAllParams(greet: String, name: String = "Jay", message: String): String {
return greet + name + ", " + message
}
Named Arguments lets us set the name of the parameter to the respective argument in in the function call.
This way instead of always sticking to the defined order of parameters, we can set our own order.
It enhances the readability of the function too as shown below.
命名参数使我们可以将参数的名称设置为函数调用中相应的参数。
这样,我们可以始终设置自己的顺序,而不必始终遵循参数的定义顺序。
如下所示,它也增强了功能的可读性。
fun main(args: Array) {
returnBooleans(a = true, b = true, c = true, d = false)
}
fun returnBooleans(a: Boolean, b: Boolean, c: Boolean, d: Boolean): Boolean {
return a && b || c && d
}
In the above code, we’re able to keep a track of each parameter name and value in the function unlike the following code where we can forget which argument is set for which parameter.
在上面的代码中,我们能够跟踪函数中每个参数的名称和值,与下面的代码不同,在这里我们可以忘记为哪个参数设置了哪个参数。
returnBooleans(true, true, true, false)
Functions in Kotlin that consist of a single expression only can be made much simpler and concise using the following syntax:
使用以下语法,可以使Kotlin中仅包含一个表达式的函数更加简单明了:
fun main(args: Array) {
print(sumOfTwo(2, 3))
}
fun sumOfTwo(a: Int, b: Int) = a + b
As shown above, single expressions can be written on the Right hand side of =
.
Single expression functions do not require setting the return type or the curly braces. Kotlin automatically infers it for you.
如上所示,单个表达式可以写在=
的右侧。
单表达式函数不需要设置返回类型或花括号。 Kotlin会自动为您推断。
We can define functions in Kotlin with a variable number of arguments using the vararg
modifier in the parameter declaration as shown below.
我们可以使用参数声明中的vararg
修饰符在Kotlin中使用可变数量的参数定义函数,如下所示。
fun main(args: Array) {
print(concatenate("Hello\n", "How are you doing?\n", "Add more words in here\n"))
}
fun concatenate(vararg word: String): String {
var result = ""
for (s in word) {
result += s
}
return result
}
Only one vararg
parameter is allowed her function.
她的函数只允许使用一个vararg
参数。
In Kotlin we can use functions as types and assign it to properties, pass them as arguments in other functions or use them as return values(High Order Functions).
在Kotlin中,我们可以将函数用作类型并将其分配给属性,将它们作为参数传递给其他函数,或将它们用作返回值(高阶函数)。
fun main(args: Array) {
val str = concatenate("Hello\n", "How are you doing?\n", "Add more words in here\n")
//str is of type String
}
fun concatenate(vararg word: String): String {
var result = ""
for (s in word) {
result += s
}
return result
}
Function types is a powerful concept and we’ll look at it in detail in High Order Functions.
函数类型是一个强大的概念,我们将在高级函数中对其进行详细介绍。
A spread operator is denoted by * and is decomposes an array into individual elements which we’ll eventually pass into the vararg
parameter as shown below.
扩展运算符用*表示,并将一个数组分解为单个元素,我们最终将其传递给vararg
参数,如下所示。
fun main(args: Array) {
val a = intArrayOf(1, 2, 3)
print(sumOfNumbers(*a))
}
fun sumOfNumbers(vararg numbers: Int): Int {
var sum = 0
for (number in numbers) {
sum += number
}
return sum
}
intArrayOf
creates an array out of the elements which is passed into the sumOfNumbers
function that’ll eventually spread the array into a vararg
.
intArrayOf
使用传给sumOfNumbers
函数的元素创建一个数组,该函数最终会将数组扩展为vararg
。
Extension Functions are used to extend some functionality to a class .
扩展功能用于将某些功能扩展到类。
fun main(args: Array) {
var x = 5
print(x.multiplyByTwo()) //10
}
fun Int.multiplyByTwo() : Int
{
return this*2
}
In classes
We can always extend a function from a class as shown below:
上课
我们总是可以从一个类扩展一个函数,如下所示:
fun main(args: Array) {
val b = Book()
b.printFunction("Hey") //member function
b.printFunction() //extension function
}
fun Book.printFunction()
{
println("Extension")
}
class Book {
fun printFunction(str: String) {
println(str)
}
}
//Following is printed on the console
//Hey
//Extension
In the above code, the extension function overloads the member function from the class.
在上面的代码中,扩展函数使类中的成员函数重载。
Infix notations are added on a function to make the function calling more cleaner and closer to the english language since we don’t need to call the function using a dot notation as we’ll be seeing shortly.
Requirements:
在函数上添加了前缀表示法,以使函数调用更简洁,更接近英语,因为我们不需要像稍后将看到的那样使用点表示法来调用函数。
要求:
An example below demonstrates the same.
下面的示例对此进行了演示。
fun main(args: Array) {
val b = Numbers()
b addNumber 5
print(b.x) //prints 15
}
class Numbers {
var x = 10
infix fun addNumber(num: Int) {
this.x = this.x + num
}
}
From the above code, we can decipher that bitwise operator and
, or
etc are infix functions in kotlin.
Also, infix notation function is used in downTo, until etc in loops in Kotlin too
从上面的代码中,我们可以判断出按位运算符and
or
等是kotlin中的中缀函数。
另外,downTo中使用了前缀表示法功能,直到Kotlin中的循环中也是如此
Tail Recursive Functions is a template that Kotlin uses to get rid of the loops in recursive functions.
Adding the tailrec
modifier to a function would write the function as a recursive one without for/while loops hence decreasing the risk of stack overflow.
Typically we can write recursive functions like this:
尾递归函数是Kotlin用来摆脱递归函数循环的模板。
在函数中添加tailrec
修饰符会将函数写为递归函数,而无需for / while循环,从而降低了堆栈溢出的风险。
通常,我们可以这样编写递归函数:
fun findFixPoint(): Double {
var x = 1.0
while (true) {
val y = Math.cos(x)
if (x == y) return x
x = y
}
}
Using tailrec
the above function should look like this:
使用tailrec
,上述功能应如下所示:
tailrec fun findFixPoint(x: Double = 1.0): Double
= if (x == Math.cos(x)) x else findFixPoint(Math.cos(x))
Note: tailrec is only valid when there is no code after the recursive call.
注意:tailrec仅在递归调用后没有代码时才有效。
Typically a factorial function is written like this:
通常,阶乘函数是这样编写的:
fun factorial(n: Long, accum: Long = 1): Long {
val soFar = n * accum
return if (n <= 1) {
soFar
} else {
factorial(n - 1, soFar)
}
}
The tail recursive function would look like:
尾递归函数如下所示:
fun main(args: Array) {
var x =calculateFact(1,5)
print(x)
}
tailrec fun calculateFact(acc: Long, n: Long): Long {
if (n == 1L) {
return acc
}
return calculateFact(n * acc, n - 1)
}
We’ve covered the basics of Functions in Kotlin in this tutorial. We’ll be looking at High Order Functions, Anonymous Functions, Inline Functions and many more things in the upcoming tutorials.
在本教程中,我们已经介绍了Kotlin中的Functions基础。 在即将到来的教程中,我们将研究高阶函数,匿名函数,内联函数以及更多内容。
References : Kotlin Docs
参考文献: Kotlin Docs
翻译自: https://www.journaldev.com/18771/kotlin-functions
kotlin函数