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函数的所有信息。

Kotlin函数 (Kotlin Functions)

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中我们使用术语函数而不是方法的主要原因之一。

功能类型 (Types of Functions)

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.

可以根据各种类别将功能定义为各种类型。 在很高的层次上,我们在以下两类中定义函数。

按范围 (By Scope)

  • Top Level Functions: These do not need a class to be enclosed in.顶级功能 :这些不需要包含类。
  • Member Functions: These are defined inside a class or Object成员函数 :这些是在类或对象内部定义的
  • Local or Nested Functions: Functions that are defined in another function fall into this type.局部或嵌套函数 :在另一个函数中定义的函数属于这种类型。

根据定义 (By definition)

  • Kotlin Standard Functions: Kotlin has its own set of functions such as main(), println() etc. defined in the standard libraryKotlin标准函数 :Kotlin在标准库中定义了自己的一组函数,例如main()println()等。
  • User defined functions: Which we write in our projects.用户定义的函数 :我们在项目中编写的函数

Kotlin函数基本语法 (Kotlin Function Basic Syntax)

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

声明和用法 (Declarations and Usage)

Let us define a function that calculates the sum of two numbers. We’ll do this in each of the types defined by scope.

让我们定义一个计算两个数字之和的函数。 我们将在范围定义的每种类型中执行此操作。

  • Top Level Functions

    fun main(args: Array<String>) {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.

    顶级功能

    要调用该函数,我们只需要传递参数作为参数即可。

  • Member Functions
    Member Functions are defined inside a class. A member function is invoked over the instance of the class using a dot operator as shown in the below code.

    fun main(args: Array<String>) {var a = A()a.sumOfTwo(2,3)}class A {fun sumOfTwo(a: Int, b: Int): Int{return a + b}}

    会员职能
    成员函数在类内部定义。 成员函数使用点运算符在类的实例上调用,如下面的代码所示。

  • Local/Nested Functions
    We can define a function inside another function. It can also be a return type of the enclosing function.
    The below code demonstrates the same.

    fun main(args: Array<String>) {sumOfDoubleOfTwo(2,3) //returns 5print(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()在第二条语句中充当嵌套函数。

单位返回类型 (Unit-Returning Types)

If there’s no return type, we can leave the return type space empty.

如果没有返回类型,我们可以将返回类型空间留空。

fun main(args: Array<String>) {helloWorld() //prints Fun says hello worldprint(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返回类型,所以我们可以不使用上述定义。

默认和命名参数 (Default and Named Arguments)

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<String>) {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<String>) {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)

单表达函数 (Single Expression Functions)

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<String>) {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会自动为您推断。

可变数量的参数– varargs (Variable Number of Arguments – varargs)

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<String>) {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参数。

作为类型的功能 (Functions as Types)

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<String>) {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.

函数类型是一个强大的概念,我们将在高级函数中对其进行详细介绍。

点差算子 (Spread Operator)

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 = 0for (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)

Extension Functions are used to extend some functionality to a class .

扩展功能用于将某些功能扩展到类。

fun main(args: Array<String>) {var x = 5print(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<String>) {val b = Book()b.printFunction("Hey") //member functionb.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)

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:

在函数上添加了前缀表示法,以使函数调用更简洁,更接近英语,因为我们不需要像稍后将看到的那样使用点表示法来调用函数。
要求:

  • Add the infix modifier before the function keyword在function关键字之前添加infix修饰符
  • Its only applicable on a member or extension function它仅适用于成员或扩展功能
  • An infix function can have only one parameter一个中缀函数只能有一个参数

An example below demonstrates the same.

下面的示例对此进行了演示。

fun main(args: Array<String>) {val b = Numbers()b addNumber 5print(b.x) //prints 15
}class Numbers {var x = 10infix 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)

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.0while (true) {val y = Math.cos(x)if (x == y) return xx = 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仅在递归调用后没有代码时才有效。

创建阶乘尾递归函数 (Creating a Factorial Tail Recursive Function)

Typically a factorial function is written like this:

通常,阶乘函数是这样编写的:

fun factorial(n: Long, accum: Long = 1): Long {val soFar = n * accumreturn if (n <= 1) {soFar} else {factorial(n - 1, soFar)}
}

The tail recursive function would look like:

尾递归函数如下所示:

fun main(args: Array<String>) {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函数

kotlin函数_Kotlin函数相关推荐

  1. kotlin内联函数_Kotlin内联函数,参数化

    kotlin内联函数 In this tutorial, we'll be looking into Kotlin inline function. We'll follow that with Re ...

  2. 【Kotlin】函数类型 ( 函数类型 | 带参数名称的参数列表 | 可空函数类型 | 复杂函数类型 | 带接收者函数类型 | 函数类型别名 | 函数类型实例化 | 函数调用 )

    文章目录 I . 函数类型 II . 带参数名的参数列表 III . 可空函数类型 IV . 复杂函数类型解读 V . 函数类型别名 VI . 带 接收者类型 的函数类型 VII . 函数类型实例化 ...

  3. kotlin内联函数let、with、run、apply、also

    最近面试被问到kotlin内联函数,这里作个简单的总结 let 在函数体内访问该对象中的属性或方法 iv_back_activity_clock.let {it.adjustViewBounds = ...

  4. Kotlin入门(9)函数的基本用法

    上一篇文章介绍了Kotlin新增的空安全机制,控制语句部分可算是讲完了,接下来将连续描述Kotlin如何定义和调用函数,本篇文章先介绍函数的基本用法. 前面几篇文章介绍控制语句之时,在setOnCli ...

  5. kotlin的入口函数

    java入口方法 package com.kushanmao.ja;/*** Created by kushanmao on 2017/7/16.*/ public class MainMethod ...

  6. 【Kotlin】Kotlin 函数总结 ( 具名函数 | 匿名函数 | Lambda 表达式 | 闭包 | 内联函数 | 函数引用 )

    文章目录 一.函数头声明 二.函数参数 1.默认参数值 2.具名参数 三.Unit 函数 四.TODO 函数抛出异常返回 Nothing 类型 五.反引号函数名 六.匿名函数 七.匿名函数的函数类型 ...

  7. Kotlin学习之函数

    函数声明 在kotlin中用关键字fun声明函数: fun double(x:Int):Int{ } 其中Int是返回值类型,x指明参数类型是为Int 函数用法 通过传统方法调用函数: val res ...

  8. Kotlin学习笔记(三):Kotlin中的函数

    一.函数的特性语法 函数的几种声明形式 //普通声明形式fun sayHello(str: String){print(str)}//允许参数有默认值,可用于方法重载fun printName(str ...

  9. Kotlin——高阶函数详解与标准的高阶函数使用

    一.高阶函数介绍 在介绍高阶函数之前,或许您先应该了解Kotlin中,基础函数的使用与定义.您可以参见Kotlin--初级篇(七):函数(方法)基础使用这边文章的用法. 在Kotlin中,高阶函数即指 ...

最新文章

  1. nginx的优先匹配规则
  2. Spring Boot 2.x基础教程:使用Swagger2构建强大的API文档
  3. Spark3.1.1 Docker镜像中修改/etc/hosts
  4. 性能测试工具MultiMechanize的使用介绍
  5. 反Secure Boot垄断:兼谈如何在Windows 8电脑上安装Linux
  6. ubuntu分辨率设置
  7. linux服务器程序乱码,Linux安装GBK/GB2312程序显示乱码的五种解决方法
  8. Simplification of Articulated Meshes (EURO 09)
  9. 那些还在传程序猿35岁职业危机
  10. 初识Redis educoder
  11. linux测试sata硬盘读写速度
  12. threejs 绘制星空
  13. html如何绘制树结构图,HTML 5 Canvas 递归画树
  14. 初恋失败让我学会推销自己
  15. android studio透明背景,使用Android Studio时出现黑色的PNG透明背景
  16. 微信小程序 保存图片 wx.saveImageToPhotosAlbum
  17. 爬虫之scrapy框架的数据持久化存储/保存为scv,json文件
  18. 饿了么“短平快”创新项目的架构取舍之道
  19. P1108 低价购买(DP)
  20. jquery添加样式

热门文章

  1. 【整理】C#2.0特性之局部类、空属类型和静态类
  2. [转载] Python pep8编码规范
  3. [转载] 快速入门(完整):Python实例100个(基于最新Python3.7版本)
  4. CodeSmith使用存档
  5. Java调用Javascript、Python算法总结
  6. PHP操作tcpdf插件生成PDF
  7. 流量限制器(Flux Limiter)
  8. 各大牛逼讲师的经典Jquery精品视频教程,大放送啦!!!(包括手机移动端JqueryWeb开发)!!!...
  9. linux shell 递归统计代码行数
  10. 从程序员到项目经理(24):慎于问敏于行 - 忠于工作不等于奴性