sealed class UIState {
data object Loading : UIState()
data class Success(val data: String) : UIState()
data class Error(val exception: Exception) : UIState()
}
fun updateUI(state: UIState) {
when (state) {
is UIState.Loading -> showLoadingIndicator()
is UIState.Success -> showData(state.data)
is UIState.Error -> showError(state.exception)
}
}
支付方式处理
在实际的业务应用中,高效地处理各种支付方式是一个常见的需求。 你可以使用密封类和 when 表达式来实现这样的业务逻辑。 通过将不同的支付方式表示为密封类的子类,可以建立一个清晰且易于管理的交易处理结构:
sealed class Payment {
data class CreditCard(val number: String, val expiryDate: String) : Payment()
data class PayPal(val email: String) : Payment()
data object Cash : Payment()
}
fun processPayment(payment: Payment) {
when (payment) {
is Payment.CreditCard -> processCreditCardPayment(payment.number, payment.expiryDate)
is Payment.PayPal -> processPayPalPayment(payment.email)
is Payment.Cash -> processCashPayment()
}
}
sealed interface ApiRequest
data class LoginRequest(val username: String, val password: String) : ApiRequest
data class LogoutRequest(val userId: String) : ApiRequest
sealed class ApiResponse
data class UserSuccess(val userData: String) : ApiResponse()
object UserNotFound : ApiResponse()
data class Error(val message: String) : ApiResponse()
fun handleRequest(request: ApiRequest): ApiResponse {
return when (request) {
is LoginRequest -> {
val user = getUserById(request.username)
if (user != null) UserSuccess(user) else UserNotFound
}
is LogoutRequest -> {
// 处理登出逻辑
UserSuccess("成功登出")
}
}
}
fun getUserById(username: String): String? {
// 模拟用户检索
return if (username == "validUser") "UserDataFor_$username" else null
}
// 导入必要的模块
import io.ktor.server.application.*
import io.ktor.server.resources.*
import kotlinx.serialization.*
// 使用 Ktor 资源定义 API 请求的密封接口
@Resource("api")
sealed interface ApiRequest
@Serializable
@Resource("login")
data class LoginRequest(val username: String, val password: String) : ApiRequest
@Serializable
@Resource("logout")
object LogoutRequest : ApiRequest
// 定义带有详细响应类型的 ApiResponse 密封类
sealed class ApiResponse {
data class UserSuccess(val user: UserData) : ApiResponse()
data object UserNotFound : ApiResponse()
data class Error(val message: String) : ApiResponse()
}
// 用于成功响应的用户数据类
data class UserData(val userId: String, val name: String, val email: String)
// 验证用户凭据的函数(用于演示)
fun isValidUser(username: String, password: String): Boolean {
// 一些验证逻辑(仅为占位符)
return username == "validUser" && password == "validPass"
}
// 处理 API 请求并提供详细响应的函数
fun handleRequest(request: ApiRequest): ApiResponse {
return when (request) {
is LoginRequest -> {
if (isValidUser(request.username, request.password)) {
ApiResponse.UserSuccess(UserData("userId", "userName", "userEmail"))
} else {
ApiResponse.Error("无效的用户名或密码")
}
}
is LogoutRequest -> {
// 假设登出操作在此示例中总是成功
ApiResponse.UserSuccess(UserData("userId", "userName", "userEmail")) // 用于演示
}
}
}
// 模拟 getUserById 调用的函数
fun getUserById(userId: String): ApiResponse {
return if (userId == "validUserId") {
ApiResponse.UserSuccess(UserData("validUserId", "John Doe", "john@example.com"))
} else {
ApiResponse.UserNotFound
}
// 错误处理也会导致 Error 响应。
}
// 主函数以演示用法
fun main() {
val loginResponse = handleRequest(LoginRequest("user", "pass"))
println(loginResponse)
val logoutResponse = handleRequest(LogoutRequest)
println(logoutResponse)
val userResponse = getUserById("validUserId")
println(userResponse)
val userNotFoundResponse = getUserById("invalidId")
println(userNotFoundResponse)
}