当前位置:   article > 正文

【第二阶段】kotlin函数引用_kotlin 引入其他文件的函数

kotlin 引入其他文件的函数

针对上篇传入函数参数我们也可以重新定义一个函数,然后在main中调用时传入函数对象
lambda属于函数类型的对象,需要把普通函数变成函数类型的对象(函数引用),使用“::”

/**
 * You can edit, run, and share this code.
 * play.kotlinlang.org
 */
fun main() {
  
     //第一种写法 使用“::”函数引用
      val info=login("kotlin","123456",::meResponseResult)
      println(info)
      
      //第二种写法 对象引用的函数引用
      val obj=::meResponseResult
     val info2=login("kotlin","123456",obj)
      println(info2)
}



//定义函数实现responseResult:(String,Int)->String):String
fun meResponseResult(msg:String,code:Int):String{
   return "登录结果:$msg,$code"
}

//模拟数据库SQLServer
const val USER_NAME_DB="kotlin"
const val USER_PWD_DB="123456"

//登录
/*
 * responseResult:(String,Int)->Unit) 传入响应结果的参数,同时也是获取响应结果的函数
 * 
 *  TODO()//Nothing类型,出现问题,终止程序
 *
 * */
private inline fun login(username:String,password:String,responseResult:(String,Int)->String):String{
    if(username==null||password==null){
        TODO("账号密码为空")//Nothing类型,出现问题,终止程序
    }
    //登录校验
    if(username.length>3&&password.length>3){
        if(isLogin(username,password)){
            //登录成功逻辑,以及处理登录成功后的业务
            //登录成功后返回响应结果,调用参数中的responseResult:(String,Int)->Unit)
             return responseResult("login success",200)
        }else{
             //登录失败逻辑,以及处理登录失败后的业务
             //登录失败后返回响应结果,调用参数中的responseResult:(String,Int)->Unit)
             return responseResult("login failed",444)
        }
    }else{
         TODO("账号密码不符合规范")//Nothing类型,出现问题,终止程序
    }
    return ""
}

//登录校验
private fun isLogin(username:String,password:String):Boolean{
    return if(username==USER_NAME_DB && password==USER_PWD_DB) true else false
}
  • 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

执行结果
在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/木道寻08/article/detail/1009271
推荐阅读
相关标签
  

闽ICP备14008679号