針對上篇傳入函數參數我們也可以重新定義一個函數,然后在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=::meResponseResultval 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
}
執行結果