廣水市建設(shè)局網(wǎng)站線上培訓(xùn)
針對上篇傳入函數(shù)參數(shù)我們也可以重新定義一個函數(shù),然后在main中調(diào)用時傳入函數(shù)對象
lambda屬于函數(shù)類型的對象,需要把普通函數(shù)變成函數(shù)類型的對象(函數(shù)引用),使用“::”
/*** You can edit, run, and share this code.* play.kotlinlang.org*/
fun main() {//第一種寫法 使用“::”函數(shù)引用val info=login("kotlin","123456",::meResponseResult)println(info)//第二種寫法 對象引用的函數(shù)引用val obj=::meResponseResultval info2=login("kotlin","123456",obj)println(info2)
}//定義函數(shù)實現(xiàn)responseResult:(String,Int)->String):String
fun meResponseResult(msg:String,code:Int):String{return "登錄結(jié)果:$msg,$code"
}//模擬數(shù)據(jù)庫SQLServer
const val USER_NAME_DB="kotlin"
const val USER_PWD_DB="123456"//登錄
/** responseResult:(String,Int)->Unit) 傳入響應(yīng)結(jié)果的參數(shù),同時也是獲取響應(yīng)結(jié)果的函數(shù)* * TODO()//Nothing類型,出現(xiàn)問題,終止程序** */
private inline fun login(username:String,password:String,responseResult:(String,Int)->String):String{if(username==null||password==null){TODO("賬號密碼為空")//Nothing類型,出現(xiàn)問題,終止程序}//登錄校驗if(username.length>3&&password.length>3){if(isLogin(username,password)){//登錄成功邏輯,以及處理登錄成功后的業(yè)務(wù)//登錄成功后返回響應(yīng)結(jié)果,調(diào)用參數(shù)中的responseResult:(String,Int)->Unit)return responseResult("login success",200)}else{//登錄失敗邏輯,以及處理登錄失敗后的業(yè)務(wù)//登錄失敗后返回響應(yīng)結(jié)果,調(diào)用參數(shù)中的responseResult:(String,Int)->Unit)return responseResult("login failed",444)}}else{TODO("賬號密碼不符合規(guī)范")//Nothing類型,出現(xiàn)問題,終止程序}return ""
}//登錄校驗
private fun isLogin(username:String,password:String):Boolean{return if(username==USER_NAME_DB && password==USER_PWD_DB) true else false
}
執(zhí)行結(jié)果