前言
infix是一个中缀函数,一个优化语法的语法糖函数的关键字,如果不会使用也不要紧,因为它并不是特别重要。但是会使用它可以大大简化代码结构让代码更容易阅读。
在 Kotlin 中,infix 函数必须满足以下条件:
-
必须是成员函数或扩展函数。
-
必须只有一个参数。
-
参数不能是可变参数(varargs),也不能有默认值。
简单使用
我们可以看看kotlin自带的中缀函数的使用,比如Pair类,它就使用了infix
public infix fun <A, B> A.to(that: B): Pair<A, B> = Pair(this, that)
我们需要创建Pair的时候只需要使用to,如下
fun getData():Pair<String,Int>{
return "name" to 1
}
举一反三,创建一个处理网络请求返回结果检查的中缀函数
在网络请求返回结果检查是否成功的时候,一些请求接口会有大量一样检查的样板代码,我们可以用中缀函数简化。
先看看不使用中缀函数如何处理
/**
* 用于简单检查retrofit2网络请求返回的Response,以减少样板代码
*/
fun retrofit2.Response<HttpResultBean<Any>>.simpleCheckRes(successCode:Int): HttpResult{
if(!this.isSuccessful){
return HttpResult.Error(-1, this.message())
}
val res = this.body()
if (res?.code == successCode){
return HttpResult.Success(res.data)
}
return HttpResult.Error(res?.code?:-1, res?.msg?:"")
}
没有中缀函数的情况下使用
/**
* 注册
* @param account 账号
* @param password 密码
*/
fun register(account: String, password: String):HttpResult{
try {
val params = mapOf(
"accountNo" to account,
"confirmPassword" to password,
"password" to password
)
val response = http.register(params)
return response.simpleCheckRes(200)
} catch (e: Exception) {
e.descriptionError().logE()
return HttpResult.Error(-1, e.descriptionError())
}
}
现在使用中缀函数改造它
/**
* 用于简单检查retrofit2网络请求返回的Response,以减少样板代码
*/
infix fun retrofit2.Response<HttpResultBean<Any>>.checkResponseIsSuccess(successCode:Int): HttpResult{
if(!this.isSuccessful){
return HttpResult.Error(-1, this.message())
}
val res = this.body()
if (res?.code == successCode){
return HttpResult.Success(res.data)
}
return HttpResult.Error(res?.code?:-1, res?.msg?:"")
}
中缀函数使用
/**
* 注册
* @param account 账号
* @param password 密码
*/
fun register(account: String, password: String):HttpResult{
try {
val params = mapOf(
"accountNo" to account,
"confirmPassword" to password,
"password" to password
)
val response = http.register(params)
return response checkResponseIsSuccess 200
} catch (e: Exception) {
e.descriptionError().logE()
return HttpResult.Error(-1, e.descriptionError())
}
}
end
本文来自博客园,作者:观心静 ,转载请注明原文链接:https://www.cnblogs.com/guanxinjing/p/19026510
本文版权归作者和博客园共有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。