Kotlin基础语法二

发布于:2025-06-12 ⋅ 阅读:(21) ⋅ 点赞:(0)
  • 匿名函数
fun main() {
    val len = "Kotlin".count()
    println(len)

    val len2 = "Kotlin".count {
        // it 等价于 K o t l i n 的字符 Char
        it == 'k'
    }
    println(len2)
}
  • 函数类型&隐式返回学习
fun main() {
    // 第一步:函数输入输出的声明
    val methodAction : () -> String

    // 第二步:对上面函数的实现
    methodAction = {
        val inputValue = 999999
        "$inputValue value" // == 背后隐式 return "$inputValue value";
        // 匿名函数不要写return,最后一行就是返回值
    }

    // 第三步:调用此函数
    println(methodAction())
}
  • 函数参数
    // 第一步:函数输入输出的声明   第二步:对声明函数的实现
    val methodAction : (Int, Int, Int) -> String = { number1, number2, number3 ->
        val inputValue = 999999
        "$inputValue Value 参数一:$number1, 参数二:$number2, 参数三:$number3"
    }
    // 第三步:调用此函数
    println(methodAction(1, 2, 3))
  • it关键字
    val methodAction2 : (String) -> String = { "$it Value" }
    println(methodAction2("DDD"))

    val methodAction3 : (Double) -> String = { "$it Value" }
    println(methodAction3(5454.5))
  • 匿名函数的类型推断
    // 匿名函数,类型推断为String
    // 方法名 : 必须指定 参数类型 和 返回类型
    // 方法名 = 类型推断返回类型
    val method1 = { v1:Double, v2:Float, v3:Int ->
       "v1:$v1, v2:$v2, v3:$v3"
    } // method1 函数: (Double, Float, Int) -> String
    println(method1(454.5, 354.3f, 99))

    val method2 = {
        3453.3f
    } // method2 函数: () -> Unit
    println(method2())

    val method3 = { number: Int ->
        number
    } // method3 函数: (Int) -> Int
    println(method3(9))
  • lambda
    // 匿名函数 == lambda表达式
    val addResultMethod = { number1 : Int, number2: Int ->
        "两数相加的结果是:${number1 + number2}"
    } // addResultMethod 函数: (Int, Int) -> String
    println(addResultMethod(1, 1))

    // 匿名函数 入参 Int,          返回 Any类型
    // lambda表达式的参数 Int,    lambda表达式的结果Any类型
    val weekResultMethod = { number: Int ->
        when(number) {
            1 -> "星期1"
            2 -> "星期2"
            3 -> "星期3"
            4 -> "星期4"
            5 -> "星期5"
            else -> -1
        }
    } // weekResultMethod 函数: (Int) -> Any
    println(weekResultMethod(2))
  • 在函数中定义参数是函数的函数
fun main() {
    loginAPI("KK", "123456") { msg: String, code: Int ->
        println("最终登录的情况如下: msg:$msg, code:$code")
    }
}

// 模拟:数据库SQLServer
const val USER_NAME_SAVE_DB = "KK"
const val USER_PWD_SAVE_DB = "123456"

// 登录API 模仿 前端
public fun loginAPI(username: String, userpwd: String, responseResult: (String, Int) -> Unit) {
    if (username == null || userpwd == null) {
        TODO("用户名或密码为null") // 出现问题,终止程序
    }

    // 做很多的校验 前端校验
    if (username.length > 3 && userpwd.length > 3) {
        if (wbeServiceLoginAPI(username, userpwd)) {
            // 登录成功
            // 做很多的事情 校验成功信息等
            // ...
            responseResult("login success", 200)
        } else {
            // 登录失败
            // 做很多的事情 登录失败的逻辑处理
            // ...
            responseResult("login error", 444)
        }
    } else {
        TODO("用户名和密码不合格") // 出现问题,终止程序
    }
}

// 登录的API暴露者 服务器
private fun wbeServiceLoginAPI(name: String, pwd: String) : Boolean {
    // kt的if是表达式(很灵活)     java的if是语句(有局限性)

    // 做很多的事情 登录逻辑处理
    // ...

    return if (name == USER_NAME_SAVE_DB && pwd == USER_PWD_SAVE_DB) true else false
}
  • Kotlin函数简略写法
    // 第一种方式
    loginAPI2("KK", "123456", { msg: String, code:Int ->
        println("最终登录的情况如下: msg:$msg, code:$code")
    })

    // 第二种方式
    loginAPI2("KK", "123456", responseResult = { msg: String, code: Int ->
        println("最终登录的情况如下: msg:$msg, code:$code")
    })

    // 第三种方式
    loginAPI2("KK", "123456") { msg: String, code: Int ->
        println("最终登录的情况如下: msg:$msg, code:$code")
    }
  • 内联函数 inline
    减少函数调用开销,将高阶函数(如 lambda 参数)的代码直接内联到调用处,避免 创建额外的函数对象,提升执行效率。
inline fun measureTime(action: () -> Unit) {
    val start = System.currentTimeMillis()
    action()
    println("耗时: ${System.currentTimeMillis() - start}ms")
}
  • 函数引用
fun main() {
    // 函数引用
    // lambda属于函数类型的对象,需要把methodResponseResult普通函数变成 函数类型的对象(函数引用)

    // loginAPI("KK", "123456", ::methodResponseResult)

    val obj = ::methodResponseResult
    val obj2 = obj
    val obj3 =  obj2

    loginAPI("KK", "123456", obj3)
}

fun methodResponseResult(msg: String, code: Int) {
    println("最终登录的成果是:msg:$msg, code:$code")
}
  • 函数类型作为返回类型
fun showMethod(info: String): (String, Int) -> String {
    println("我是show函数 info:$info")

    // return 一个函数 匿名函数
    return { name: String, age: Int ->
        "我就是匿名函数:我的name:$name, age:$age"
    }
}

fun main() {
    val r = show("学习KT语言")
    // r 是show函数的 返回值
    val niming_showMethod = showMethod("show")
    // niming_showMethod 是 showMethod函数的返回值 只不过这个返回值 是一个 函数
    // niming_showMethod == 匿名函数
    println(niming_showMethod("Derry", 33))
}
  • 匿名函数与具名函数
    // 匿名函数
    showPersonInfo("lisi", 99, '男', "学习KT语言") {
        println("显示结果:$it")
    }

    // 具名函数 showResultImpl
    showPersonInfo("wangwu", 89, '女', "学习C++语言", ::showResultImpl)