介紹
當(dāng)對(duì)象具有來自有限集的類型之一(密封類對(duì)子類有限制),但不能具有任何其他類型時(shí),使用密封類。(例如網(wǎng)絡(luò)請(qǐng)求數(shù)據(jù)只能是請(qǐng)求成功霹肝、請(qǐng)求失敗)
class Expr
class Const(val value: Int) : Expr
class Sum(val left: Expr, val right: Expr) : Expr
fun eval(e: Expr): Int =
when (e) {
is Const -> e.value
is Sum -> eval(e.right) + eval(e.left)
else ->
throw IllegalArgumentException("Unknown expression")
}
如果添加一個(gè)新的類(NotANumber)上邊會(huì)走else塑煎。下邊Sealed會(huì)在編譯時(shí)提示你沫换。
sealed class Expr
class Const(val value: Int) : Expr()
class Sum(val left: Expr, val right: Expr) : Expr()
object NotANumber : Expr()
fun eval(e: Expr): Int =
when (e) {
is Const -> e.value
is Sum -> eval(e.right) + eval(e.left)
NotANumber -> java.lang.Double.NaN
}
使用Demo
網(wǎng)絡(luò)請(qǐng)求 數(shù)據(jù)回調(diào)covert
/**
* 密封類
* 轉(zhuǎn)換接口請(qǐng)求的數(shù)據(jù)
* success 數(shù)據(jù)正常返回
* error 數(shù)據(jù)異常情況
*/
sealed class ApiResult<out T:Any> {
data class Success<out T:Any>(val data:T):ApiResult<T>()
data class Error(var errorCode:ErrorCode,var errorMsg:String):ApiResult<Nothing>()
}
enum class ErrorCode{
NETERROR,
ERROR,
NOTLOGIN
}
class Repository {
fun login(phone:String,pwd:String):ApiResult<String>{
//請(qǐng)求接口 api.login()
//轉(zhuǎn)換接口請(qǐng)求數(shù)據(jù)
return if (phone.isNotEmpty()){
ApiResult.Success("success")
}else{
ApiResult.Error(ErrorCode.ERROR,"找不到www.xxx.com")
}
}
}
class LoginModule {
val repo by lazy { Repository() }
fun login(){
val result = repo.login("1232131231", "123")
when(result){
is ApiResult.Success ->{
println(result.data)
}
is ApiResult.Error ->{
when(result.errorCode){
ErrorCode.ERROR ->{}
ErrorCode.NOTLOGIN ->{}
}
}
}
}
}
注意事項(xiàng)
- 所有子類必須在密封類同一文件聲明
- 密封類是抽象的不能實(shí)例化
- 不能創(chuàng)建非私有構(gòu)造函數(shù),因?yàn)槟J(rèn)是private的