Kotlin局部函数

作者: 程序员丶星霖 | 来源:发表于2019-07-12 10:16 被阅读7次

Kotlin还支持在函数体内部定义函数,这种函数称为局部函数。

在默认情况下,局部函数对外部是隐蔽的,局部函数只能在其封闭函数内有效,其封闭函数也可以返回局部函数,以便程序在其他作用域中使用局部函数。

fun main(args: Array<String>) {
    println(getMathFunc("square", 3))
    println(getMathFunc("cube", 3))
    println(getMathFunc("", 3))
}

fun getMathFunc(type: String, nn: Int): Int {
    fun square(n: Int): Int {
        return n * n
    }

    fun cube(n: Int): Int {
        return n * n * n
    }

    fun factorial(n: Int): Int {
        var result = 1
        for (index in 2..n) {
            result *= index
        }
        return result
    }
    when (type) {
        //调用局部函数
        "square" -> return square(nn)
        "cube" -> return cube(nn)
        else -> return factorial(nn)
    }
}

输出结果:

9
27
6

学海无涯苦作舟

我的微信公众号.jpg

相关文章

网友评论

    本文标题:Kotlin局部函数

    本文链接:https://www.haomeiwen.com/subject/cytpfctx.html