赞
踩
针对上篇传入函数参数我们也可以重新定义一个函数,然后在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 }
执行结果
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。