1. Wei shenme xuyao fun interface
Dang ni yi jing xi guan le lambdas(bi ru { x -> x > 0 } )he function types( (Int) -> Boolean ),ni keneng hui juede dan du you yi ge fun interface de gouzao shi「wei le gouzao er gouzao」de nadeng jiangpin。 Dan zai shijian zhong,ta jiejue de shi yi ge hen shijiyong de wenti: ruhe gei xingwei mingming,yi ji ruhe zai API li dui xingwei dacheng gongshi,rang daima du qi lai xiang zhengchang wenben,er bu shi yi dui kuohao de dui die.
Xiangxiang ni zai xie yi ge yingyong:li mian you「command handler」「validation rule」「formatting strategy」deng deng. Cong xingshi shang lai shuo zhe xie dou shi functions. Dan ru guo ni dao chu dou dai zhe xiang (AppState, List<String>) -> String zhe yang de types,na ren nao hen kuai jiu hui guore. fun interface rang ni ke yi shuo:「zhe ge type jiu shi command handler」,yixia zi jiu bian de geng qingchu le.
Zai Kotlin li,suowei functional(SAM)interface,zhi de shi yi ge you zhiyou yi ge abstract method de interface, er Kotlin ke yi ba lambda「tianjin qu」zuo wei ta de shixian(SAM zhuanhuan)。
Yong renhua fangshi li jie SAM:「yi ge dongzuo」zuo wei contract
Wo men ba SAM cong guifan wenzi fan yi dao geng shenghuo hua de yuyan. Putong interface changchang miaoshu yi ge「shenfen dai zhe hen duo zeren」de dongxi:bi ru 「hui hua hua」、「hui baocun」、「hui huibao mingzi」、「ke yi bei guanbi」. Zhe hen zhengchang.
SAM interface ze shi yi ge guanyu yi ge dongzuo de interface,xiang yi ge zhiyou yi ge gongneng de anniu. Bi ru:「jiancha shuzi」、「chuli shijian」、「geshi hua zifuchuan」、「zhixing mingling」. Dang ni xiang yao yi ge you mingming de contract(rang function signatures du qi lai you yiyi), dan you xiang yao kuaisu di gei chu shixian — yong lambda,bu yong xie yi da duan liyi de object : ..., zhe shi SAM hen youyong de shihou.
Zai Kotlin li,functional/SAM interface ke yi you renyi duoshao fei abstract functions, dan abstract method bixu ganghao zhiyou yi ge.
Wei shenme bu zhijie yong function type
Zhe li yiding hui you yi ge hebu qingli de wenti:「Na wei shenme yao yinru fun interface CommandHandler, ru guo wo ke yi xie typealias CommandHandler = (AppState, List<String>) -> String?」
Guanjian zai yu:functional interface bing bu deng yu typealias yi ge functional type. Interface ti gong you mingming de contract,hai ke yi you additional de fei abstract methods; er typealias zhi shi yi ge existing type de bie ming.
Cong shijian jiaodu lai kan,chayi changchang shi zheyang:
| Xuanzhe shenme | Shenme shihou fangbian | De dao shenme |
|---|---|---|
| Function type (A) -> B | Neibu luoji,「kuaisu chuanjin lai yong wan jiu suan」 | Zuidi shiti shuliang,zuida jianjie |
| fun interface | Public API,「zhe shi jiegou li hen zhongyao de yige juese」 | Hao dong de type name + ke yi yong default methods kuozhan interface |
Ye jiu shi shuo,fun interface shi yi zhong ba xingwei biancheng you mingming、you domain yiyi de dongxi de fangfa. Dang ni kan dao CommandHandler,ni zhi dao ta de role. Dang ni kan dao (AppState, List<String>) -> String, ni zhi dao de zhi you xingshi(er qie bu yiding hen kuai fan ying guo lai)。
2. Ruhe shengming fun interface,yi ji SAM zhuanhuan zenme gongzuo
Zhe li de guanjian zi jiu shi interface qianmian na ge fun. Ta bu shi「gen FP you guan」de yi yi shang de「functional interface」,er shi yi ge jishu biaoqian: 「Bianyiqi,qing yunxu SAM zhuanhuan,bing jiancha zhiyou yi ge abstract method de guize」。
Zui xiaoqi de li zi:
fun interface IntPredicate {
fun accept(x: Int): Boolean
}
Zhe li accept shi weiyi de abstract method. Suoyi Kotlin ke yi zheyang yong:
fun interface IntPredicate {
fun accept(x: Int): Boolean
}
fun main() {
val isEven = IntPredicate { x -> x % 2 == 0 }
println(isEven.accept(7)) // false
println(isEven.accept(10)) // true
}
Zhongdian shi: wo men shi zai chuangjian yi ge interface duixiang,zhi shi Kotlin yunxu ni yong yi ge lambda lai miaoshu ta.
SAM zhuanhuan li dao di「zhuanhuan」le shenme
Dang renmen shuo「lambda bian cheng interface」,hen rongyi rang ren xiangxiang cheng yi zhong shenmi de biandao: hao xiang lambda tu ran bian cheng le class. Qishi zhe shi yi ge hen hao li jie de xiao jishu: bianyiqi shengcheng yi ge shixian le interface de duixiang, ranhou ba ni de lambda dangzuo weiyi method de body.
Yong tu jie de fangshi ke yi zheyang biaoshi:
flowchart LR
A["Lambda: { x -> x % 2 == 0 }"] --> B["SAM conversion by the compiler"]
B --> C["An object implementing IntPredicate"]
C --> D["Method accept(x) calls the lambda"]
Ye jiu shi shuo,SAM zhuanhuan shi yi zhong gao su bianyiqi:「qing bang wo shengcheng yi ge interface shixian,luoji zai zhe li」de fangfa. Dang ni xiang yao ba yige dongxi cunqilai huo chuanlai chuanqu,er ni yao de bu shi「zhishi yi ge function」,er shi mou ge yiding contract de duixiang, zhe jiu tebie fangbian.
object : ... yu SAM lambda:yiyi yi yang,xiefa bu tong
SAM zhuanhuan de jiazhi tongchang zai ni ba liang duan daima fang zai yiqi kan de shihou jiu hen mingxian: yi duan shi「Java niandai de anonymous class fengge」,ling yi duan shi「Kotlin fengge」.
Tong yang de yiyi(jiance ou shu)zai mei you SAM zhuanhuan shi:
fun interface IntPredicate {
fun accept(x: Int): Boolean
}
fun main() {
val isEven = object : IntPredicate {
override fun accept(x: Int): Boolean = x % 2 == 0
}
println(isEven.accept(7)) // false
}
Er yong SAM zhuanhuan shi:
fun interface IntPredicate {
fun accept(x: Int): Boolean
}
fun main() {
val isEven = IntPredicate { it % 2 == 0 }
println(isEven.accept(7)) // false
}
Liang zhong xiefa dou hui chuangjian yi ge duixiang,ta hui accept。Dan di er zhong xiefa bu xuyao xie na xie duoyu de banban daima.
3. Shili: yong fun interface zuo CLI commands handlers
Xianzai wo men ba zhe ge zhuti la dao geng you shengmingli de changjing. Jia she wo men you yi ge yongyu jizhang de console app(jiao ta BudgetBuddy)。 Yi qian wo men hen keneng hui xie yi ge hen da de when (command) ranhou ba luoji sai jin qu. Zhe yang dangran keyi gongzuo,dan ta hui bu duan zhangda,zuihou kan qi lai xiang yi ge monolith.
Wo men jin yi bu: ba commands handlers ti qu dao yige data structure(bi ru Map)li, dan tongshi rang handler shi you mingming de contract,er bu shi luo luo de function. Zhe ge changjing xia fun interface feichang heshi.
Zui xiaoqi de model he handler contract
Xian cong jidan de model kaishi:
data class Expense(
val id: Int,
val title: String,
val amount: Double
)
class AppState(
val expenses: MutableList<Expense>
)
Xianzai shengming command handler de contract:
fun interface CommandHandler {
fun handle(state: AppState, args: List<String>): String
}
Wei shenme wo men fanhui String?Yinwei xianzai wo men bu xiang rang result model tai fuzha. Rang handler zhijie fanhui yiduan wenzi,ranhou main da yin chu lai jiu hao. Zhe dui jiaoxue hen youyong,ye bu xuyao yinru xin de shiti.
Zuo yi ge output util:
fun renderExpenses(expenses: List<Expense>): String {
if (expenses.isEmpty()) return "There are no expenses yet."
return expenses.joinToString(separator = "\n") { e ->
"#${e.id}: ${e.title} — ${e.amount}"
}
}
Xianzai tongguo SAM zhuanhuan chuangjian「commands registry」:
fun buildHandlers(): Map<String, CommandHandler> {
return mapOf(
"help" to CommandHandler { _, _ ->
"Commands: help, add, list, exit"
},
"list" to CommandHandler { state, _ ->
renderExpenses(state.expenses)
}
)
}
Qing zhuyi yi ge zhongyao dian:CommandHandler { state, args -> ... } shi tongguo lambda chuangjian handler duixiang.
Zai main li diaoyong handlers
Jie xia lai jinru command read loop. Wo men bu hui qu zuo yi ge hen zhengshi de parser,zhi xie yi ge jidan ban: command shi di yi ge word,args shi qita bufen.
fun main() {
val state = AppState(mutableListOf())
val handlers = buildHandlers()
while (true) {
print("> ")
val parts = readln().trim().split(" ")
val cmd = parts.firstOrNull()?.lowercase() ?: continue
val args = parts.drop(1)
if (cmd == "exit") break
val handler = handlers[cmd]
val result = handler?.handle(state, args) ?: "Unknown command: $cmd"
println(result)
}
}
Zhe li de yiyi shang de shouyi shi:main xianzai zhuyao zuo dispatching,er bu shi xie commands luoji. Ta du qi lai xiang:「du le → zhao handler → diao yong → shuchu」,xi jie dou zai handlers li.
Dang ni wen「wei shenme bu neng bianyi」: signature bixu yizhi
Dang SAM zhuanhuan「meiyou fasheng」shi,yuanyin jiben dou hen zhijie:lambda de parameters huo return type gen abstract method bu pipei.
Bi ru:
fun interface IntTransformer {
fun apply(x: Int): Int
}
Zhe yang xie shi dui de:
val plusOne = IntTransformer { it + 1 }
println(plusOne.apply(10)) // 11
Dan zhe yang jiu bu xing le(fan hui le Boolean,dan xuyao Int):
val wrong = IntTransformer { it > 0 } // will not compile
Dui chuxue zhe lai shuo,zhe kan qi lai xiang「bianyiqi tai tiaoti」。Qishi ta zai jiu ni,bu rang ni jinru yi ge guai guai de shijie: mingming handler「yinggai fanhui Int」,ni que fanhui le「true/false」.
fun interface yu closures:hen fangbian,dan ye keneng ba state cang qilai
Lambda zui「yinxian」de bufen bu shi syntax,er shi lambda ke yi「capture」wai bu bianliang. Zhe jiao zuo closure(closures)。
Li zi:
fun interface CounterStep {
fun next(): Int
}
fun main() {
var x = 0
val step = CounterStep {
x += 1
x
}
println(step.next()) // 1
println(step.next()) // 2
}
Jishu shang zhe yang dangran keyi. Dan cong architecture jiaodu lai shuo,ni xianzai chuangjian le yi ge yilai wai bu var x de handler. Ru guo zhe yang de handler bei yi dong dao ling yi ge file huo module,ta jiu hui bi jiao nan li jie he test: state bu zai duixiang nei bu,er shi「zai wai mian,dan you zai pangbian」.
You shihou zhe mei wenti(bi ru yi ge xiao xiao de counter),dan zai shiji yingyong daima li,you yi ge youyong de xinfa: ru guo behavior bian de zhongyao er qie hui changqi cunzai,zuihao rang state shi xianxing de(bi ru zai class / app state structure li), er bu shi ou ran bei lambda capture.
4. Shi yong fun interface he SAM zhuanhuan de changjian cuowu
Cuowu №1: xie le you liang ge abstract methods de fun interface,ranhou qi guai wei shenme Kotlin baocuo.
SAM zhuanhuan zhi you zai abstract method ganghao zhiyou yi ge de shihou cai neng fasheng. Yi dan ni tian le di er ge abstract method, zhe ge interface jiu bu zai shi functional,lambda ye jiu wu fa dan yi di「cheng wei shixian」. Zhe bu shi Kotlin gao qipi,er shi fangzhi ambiguity de baohu.
Cuowu №2: ba「functional interface」gen「function type」hun wei yi tan,zuihou API de yiyi diu le.
Dang ni zai function li kuaisu filter yige list — (Expense) -> Boolean hen hao yong. Dan ru guo ni zai sheji yi ge you role de layer(bi ru「command handler」「validator」),function type hen rongyi biancheng「yanjing de mima」. fun interface zheng shi wei le rang behavior you mingzi,bing qie neng dangzuo domain yuyan de yi bufen bei yuedu.
Cuowu №3: lambda de signature gen abstract method bu yizhi,ranhou juede SAM meiyou gongzuo.
SAM zhuanhuan de qian ti shi types dui shang. Ru guo method xuyao String,dan ni xie de lambda fanhui Int, bianyiqi jiu hui hen laoshi di shuo:「wo bu neng yong zhe ge qu ti huan na ge」. Tongchang youyong de banfa shi: mingque biaozhu lambda parameters,kan kan daodi yuqi dai shenme: { x: Int -> ... } er bu shi { it -> ... }.
Cuowu №4: zai lambda li capture wai bu var,dao zhi yin cang de mutability.
Closure ben shen shi zhengchang mechanism. Dan ru guo ni kai shi ba app de zhongyao state cang zai closures li, daima hui bian de hen nan debug: ni bu qingchu dao di shi shei、shenme shihou gai le bianliang. Zuihao ba「guanfang」state fang zai AppState / classes li,lambda jinliang yong zuo pure(huo jiejin pure)actions.
Cuowu №5: ba fun interface biancheng「method laji tong」,shi qu「yi ge dongzuo」de benyi.
Mei cuo,functional interface ke yi you additional methods,dan ta men bixu shi fei abstract de. Zai shijian zhong zhe shi yi ge xinhao: ru guo ni kai shi tian jia hen duo luoji he bu tong zeren — ye xu zhe yi jing bu zai shi SAM contract, er shi yi ge putong interface. SAM hao jiu hao zai ta de「dan yi cao zuo」: yi ge method — yi ge responsibility.
GO TO FULL VERSION