• 【Kotlin精简】第4章 函数


    1 简介

    函数是用来运行代码的载体,可以在一个函数里编写很多行代码,当运行这个函数时,函数中的所有代码会全部运行。
    Kotlin中的函数同Java完全面向对象的规则不太一样,在Kotlin的世界里,函数也是准C位的,同面向对象一样属于一等公民,Kotlin也提倡函数式编程
    Kotlin中的函数分为普通函数中缀函数局部函数泛型函数尾递归函数扩展函数内联函数高阶函数lambada函数
    在这里插入图片描述

    2 普通函数

    使用fun关键字创建一个函数。

    class Func {
    
        fun main(){
    
            // 1.调用类外部的方法
            // Kotlin 函数可以在文件顶层声明,这意味着你不需要像一些语言
            // 如 Java、C# 与 Scala 那样需要创建一个类来保存一个函数。
            // 此外除了顶层函数,Kotlin 中函数也可以声明在局部作用域、作为成员函数以及扩展函数。
            outFunc()
    
            // 2.调用五返回值函数,Unit可省略不写
            logString(100)
    
            // 3.调用普通函数,有返回值
            val num = double(10)
    
            // 4.调用普通单表达式函数,有返回值
            val num2 = double2(10)
    
            // 5.调用普通函数,参数有默认值的情况
            // 除了str以外其余的参数名都含有默认值,我们可以使用默认调用。
            // 或者指定要具体参数名调用,没指定的情况使用默认参数值
            val str = "NO.1"
            reformat(str,
                normalizeCase = true,
                wordSeparator = '_'
            )
    
            // 6.调用可变参数的函数,使用vararg修饰参数
            // 当我们已经有一个数组类型的参数的时候,
            // 我们可以用扩展符(*)来作为参数传入
            val arr = arrayOf(1,2,3)
            val list = asList(*arr, 4,5) // list: 1,2,3,4,5
    
            // 7.继承重写的函数,不能有默认值
            class B : A() {
                override fun foo(i: Int) { }
            }
    
        }
    
        private fun double(x: Int): Int {
            return 2 * x
        }
    
        private fun double2(x: Int): Int = x * 2 // 可简写:fun double(x: Int) = x * 2
    
        // 没有返回值类似Java的void,Unit可以不写
        private fun logString(x:Int):Unit{ Log.i("NormalFunc", x.toString()) }  //等同于 fun test(x:Int){ print(x) }
    
        // 默认参数函数
        private fun reformat(str: String,
                             normalizeCase: Boolean = true,
                             upperCaseFirstLetter: Boolean = true,
                             wordSeparator: Char = ' ') {
        }
    
        // 这里的T代表泛型,总是泛型总是出现在函数名的前面
        private fun <T> asList(vararg ts: T): List<T> {
            val result = ArrayList<T>()
            for (t in ts) // ts is an Array
                result.add(t)
            return result
        }
    }
    
    // 实际上会编译成类中的静态方法
    fun outFunc(){
    
    }
    
    open class A {
        open fun foo(i: Int = 10) { }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74

    fun(function的简写)是定义函数的关键字,无论定义什么函数,都一定要使用fun来声明。

    3 中缀函数

    标有 infix关键字的函数也可以使用中缀表示法(忽略该调用的点与圆括号)调用。中缀函数满足以下条件:

    1. 它们必须是成员函数或扩展函数。
    2. 它们必须只有一个参数。
    3. 其参数不得接受可变数量的参数且不能有默认值。
    infix fun Int.shl(x: Int): Int { …… }
    
    // 用中缀表示法调用该函数
    1 shl 2
    
    // 等同于这样
    1.shl(2)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    中缀函数调用的优先级低于算术操作符型转换以及 rangeTo 操作符。

    1 shl 2 + 3 等价于 1 shl (2 + 3)
    另一方面,中缀函数调用的优先级高于布尔操作符 &&||is-in-检测以及其他一些操作符。
    a && b xor c 等价于 a && (b xor c)
    a xor b in c 等价于 (a xor b) in c

    4 局部函数

    Kotlin 支持局部函数,即一个函数在另一个函数内部

    fun dfs(graph: Graph) {
        fun dfs(current: Vertex, visited: MutableSet<Vertex>) {
            if (!visited.add(current)) return
            for (v in current.neighbors)
                dfs(v, visited)
        }
    
        dfs(graph.vertices[0], HashSet())
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    局部函数可以访问外部函数(闭包)的局部变量。在上例中,visited 可以是局部变量:

    fun dfs(graph: Graph) {
        val visited = HashSet<Vertex>()
        fun dfs(current: Vertex) {
            if (!visited.add(current)) return
            for (v in current.neighbors)
                dfs(v)
        }
    
        dfs(graph.vertices[0])
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    5 泛型函数

    和其他语言一样,Kotlin是可以使用泛型

    5.1 泛型

    class Box<T>(t: T) {
        var value = t
    }
    
    • 1
    • 2
    • 3

    我们在Java中使用泛型的时候,考虑一下情况

    // Java
    interface Collection<E> …… {
      void addAll(Collection<E> items);
    }
    // Java
    void copyAll(Collection<Object> to, Collection<String> from) {
      to.addAll(from);
      // !!!对于这种简单声明的 addAll 将不能编译:
      // Collection 不是 Collection 的子类型
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    为了保证类型安全Java中不允许我们进行这样的操作,如果需要执行这种操作我们需要使用通配符

    interface Collection<E> …… {
      void addAll(Collection<? extends E> items);
    }
    
    • 1
    • 2
    • 3

    ? extend E代表通配符类型,此方法接受E或者E的一些子类,这是没有必要的因为我们知道Object是String 的父类。
    Kotlin中我们有了更简单的方式,使用out关键字来表示

    // Java
    interface Source<T> {
      T nextT();
    }
    // Java
    void demo(Source<String> strs) {
      Source<Object> objects = strs; // !!!在 Java 中不允许
      // ……
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    interface Source {
    fun nextT(): T
    }

    fun demo(strs: Source) {
    val objects: Source = strs // 这个没问题,因为 T 是一个 out-参数
    // ……
    }
    这里的out指明了他是一个可读的,但不是可写的,当一个类 C 的类型参数 T 被声明为 out 时,它就只能出现在 C 的成员的输出-位置,但回报是 C 可以安全地作为 C的超类。
    同理还有in关键字,它代表的意思就是,只可以被消费而不可以被生产,不可以作为返回值类型使用。

    可以看出in 和out类似java中的super和extend,指定了一个类型的下界和上界。

    interface Comparable<in T> {
        operator fun compareTo(other: T): Int
    }
    
    fun demo(x: Comparable<Number>) {
        x.compareTo(1.0) // 1.0 拥有类型 Double,它是 Number 的子类型
        // 因此,我们可以将 x 赋给类型为 Comparable  的变量
        val y: Comparable<Double> = x // OK!
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    5.2 泛型中的函数

    对于泛型函数我们需要把它放在函数名之前

    fun <T> singletonList(item: T): List<T> {
        // ……
    }
    
    fun <T> T.basicToString(): String {  // 扩展函数
        // ……
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    6 尾递归函数

    Kotlin 支持一种称为尾递归的函数式编程风格。

    val eps = 1E-10 // "good enough", could be 10^-15
    
    tailrec fun findFixPoint(x: Double = 1.0): Double =
        if (Math.abs(x - Math.cos(x)) < eps) x else findFixPoint(Math.cos(x))
    
    // 传统写法
    val eps = 1E-10 // "good enough", could be 10^-15
    
    private fun findFixPoint(): Double {
        var x = 1.0
        while (true) {
            val y = Math.cos(x)
            if (Math.abs(x - y) < eps) return x
            x = Math.cos(x)
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    要符合 tailrec 修饰符的条件的话,函数必须将其自身调用作为它执行的最后一个操作。

    7 扩展函数

    声明一个扩展函数,我们需要一个接受者类型也就是被扩展的类型作为他的前缀

    fun MutableList<Int>.swap(index1: Int, index2: Int) {
        val tmp = this[index1] // “this”对应该列表
        this[index1] = this[index2]
        this[index2] = tmp
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    这里只针对一种类型,我们可以使用泛型来适配

    fun <T> MutableList<T>.swap(index1: Int, index2: Int) {
        val tmp = this[index1] // “this”对应该列表
        this[index1] = this[index2]
        this[index2] = tmp}
    
    • 1
    • 2
    • 3
    • 4

    8 内联函数

    内联函数会将方法直接写在调用的地方,简而言之就是内联函数等于将代码块,copy到调用的地方。

        inline fun sum(a: Int): Int {
            var count = 8
            count += a
            return count
        }
    
        fun main() {
            println((sum(10)+ sum(5)).toString())
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    使用Java查看字节码之后

    public final class Test {
       public final int sum(int a) {
          int $i$f$sum = 0;
          int count = 8;
          int count = count + a;
          return count;
       }
    
       public final void main() {
          int a$iv = 10;
          int $i$f$sum = false;
          int count$iv = 8;
          int count$iv = count$iv + a$iv;
          int var10000 = count$iv;
          a$iv = 5;
          $i$f$sum = false;
          count$iv = 8;
          count$iv = count$iv + a$iv;
          DriverManager.println(String.valueOf(var10000 + count$iv));
       }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    8.1 内联关键字

    noinline: 让原本的内联函数变为不是内联的,保留 数据 特征

    如果一个内联函数的参数里包含 lambda表达式,也就是函数参数,那么该形参也是 inline 的,举个例子:

    inline fun test(inlined: () -> Unit) {...}
    
    //这里有个问题需要注意,如果在内联函数的内部,函数参数被其他非内联函数调用,就会报错
    //我们需要变为不为内联的
    inline fun test(noinline inlined: () -> Unit) {...}
    
    • 1
    • 2
    • 3
    • 4
    • 5

    *crossinline: 非局部返回标记,为了不让lamba表达式直接返回内联函数,所做的标记
    相关知识点:我们都知道, Kotlin中,如果一个函数中,存在一个lambda表达式,在该lambda中不支持直接通过return退出该函数的,只能通过return@XXXinterface这种方式

    fun test() {
    innerFun {
    return //非局部返回,直接退出 test() 函数。
    }
    inline fun innerFun(a: () -> Unit) {
    a()
    }
    
    //设置为crossinline之后
    fun test() {
    innerFun {
    return //这里这样会报错,只能 return@innerFun
    }
    
    //以下代码不会执行
    println("test...")
    }
    
    inline fun innerFun(crossinline a: () -> Unit) {
    a()
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    reified 直接使用泛型的类型

    fun <T> TreeNode.findParentOfType(clazz: Class<T>): T? {
        var p = parent
        while (p != null && !clazz.isInstance(p)) {
            p = p.parent
        }
        @Suppress("UNCHECKED_CAST")
        return p as T?
    }
    //使用的时候
    treeNode.findParentOfType(MyTreeNode::class.java)
    
    //我们只希望
    inline fun <reified T> TreeNode.findParentOfType(): T? {
        var p = parent
        while (p != null && p !is T) {
            p = p.parent
        }
        return p as T?
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    函数是内联的,不需要反射,正常的操作符如 !isas 现在都能用了。此外,我们还可以按照上面提到的方式调用它:myTree.findParentOfType()

    9 高阶函数和Lambada

    Kotlin中的函数是头等的,它可以出现在数据结构,函数的参数,成员变量中出现。

    fun <T, R> Collection<T>.fold(
        initial: R, 
        combine: (acc: R, nextElement: T) -> R
    ): R {
        var accumulator: R = initial
        for (element: T in this) {
            accumulator = combine(accumulator, element)
        }
        return accumulator
    }
    //
    val items = listOf(1, 2, 3, 4, 5)
    
    // Lambdas 表达式是花括号括起来的代码块。
    items.fold(0, { 
        // 如果一个 lambda 表达式有参数,前面是参数,后跟“->”
        acc: Int, i: Int -> 
        print("acc = $acc, i = $i, ") 
        val result = acc + i
        println("result = $result")
        // lambda 表达式中的最后一个表达式是返回值:
        result
    })
    //
    // lambda 表达式的参数类型是可选的,如果能够推断出来的话:
    val joinedToString = items.fold("Elements:", { acc, i -> acc + " " + i })
    -
    
    
    // 函数引用也可以用于高阶函数调用:
    val product = items.fold(1, Int::times)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    参数 combine 具有函数类型(R, T) -> R,因此 fold 接受一个函数作为参数, 该函数接受类型分别为 RT 的两个参数并返回一个 R 类型的值。 在 for-循环内部调用该函数,然后将其返回值赋值给 accumulator

      //使用typealias 来指定函数别名
    typealias ClickHandler = (Button, ClickEvent) -> Unit
    //如果我们函数的最后一个参数是一个lambda,可以写在括号外卖也可以写在括号里面
    
    fun foo(bar: Int = 0, baz: Int = 1, qux: () -> Unit) { /*……*/ }
    
    foo(1) { println("hello") }     // 使用默认值 baz = 1
    foo(qux = { println("hello") }) // 使用两个默认值 bar = 0 与 baz = 1
    foo { println("hello") }        // 使用两个默认值 bar = 0 与 baz = 1
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    9.1 函数类型的实例化

    函数类型也和普通类型一样,代表了一类实例,一般由 (R,T)->R这种表示,可以通过 lambda表达式 、匿名函数、使用已经声明的接口可调用的引用(顶层,局部,成员,扩展函数等),使用实现函数类型接口的自定义实例类。

    //lambda
    val s =  { a:Int, b:Int -> a + b }
    //匿名函数
     fun(s: String): Int { return s.toIntOrNull() ?: 0 }
    
    //使用顶层函数的引用
    val stringPlus: (String, String) -> String = String::plus//引用了plus
    //实现函数类型的接口
    class IntTransformer: (Int) -> Int {
        override operator fun invoke(x: Int): Int = TODO()
    }
    
    val intFunction: (Int) -> Int = IntTransformer()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    如果lambda表达是的参数未被使用,可以使用下划线代替

    fun test( handler: (x:Int,y:Int)->Unit){
        handler.invoke(2,3)
    }
    fun test2(){
      test ({ a:Int, b:Int-> a})//第一次完整调用
    //最后一个参数是lambda表达式,可以写在括号外面
     test { a:Int, b:Int-> a}
    //可以由于a,b的类型指定,可以省却类型
      test{a,b->a}
    //b参数未被使用,下划线代替
      test{a,_->a}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    9.2 函数类型的实例调用

    调用函数类型的实例的时候,可以通过invoke方法调用,也可以直接使用名称调用。

    val stringPlus: (String, String) -> String = String::plus
    println(stringPlus.invoke("<-", "->"))
    println(stringPlus("Hello, ", "world!")) 
    
    • 1
    • 2
    • 3

    如果该值具有接收者类型,那么应该将接收者对象作为第一个参数传递。 调用带有接收者的函数类型值的另一个方式是在其前面加上接收者对象, 就好比该值是一个1.foo(2)

    val intPlus: Int.(Int) -> Int = Int::plus
    
    println(intPlus.invoke(1, 1))
    println(intPlus(1, 2))
    println(2.intPlus(3)) // 类扩展调用
    
    • 1
    • 2
    • 3
    • 4
    • 5

    带有接收者的函数类型
    (A.(B)->C)扩展函数类似,在函数的内部可以使用接受者对象的成员函数和变量

    val sum: Int.(Int) -> Int = { other -> plus(other) } //这里我们调用了接受者对象的函数 plus
    
    //声明一个对象
    class HTML {
        fun body() { …… }
    }
    
    //申明一个函数他的
    fun html(init: HTML.() -> Unit): HTML {
        val html = HTML()  // 创建接收者对象
        html.init()        // 接受者类型调用
        init(html)          //函数式调用
        init.invoke(html)   //普通调用
        return html
    }
    
    html {       // 带接收者的 lambda 由此开始
        body()   // 调用该接收者对象的一个方法
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    在这里插入图片描述
    在这里插入图片描述

  • 相关阅读:
    leetcode算法题--求1+2+…+n
    【二叉树的遍历】
    条例13~17(资源管理)
    C语言文件操作
    Python bug: TypeError: unhashable type: ‘dict‘ or ‘list‘
    Lecture 9 Semaphores Ⅰ(信号量)
    vue实战-完全掌握Vue自定义指令
    nginx参数调优能提升多少性能
    物联网iot全称
    3D WEB轻量化引擎HOOPS Commuicator技术概览(一):数据导入与加载
  • 原文地址:https://blog.csdn.net/u010687761/article/details/133237519