本文首發於公眾號“AntDream”,歡迎微信搜索“AntDream”或掃描文章底部二維碼關注,和我一起每天進步一點點
在Kotlin中,限制函數參數的取值範圍和取值類型可以通過多種方式實現,包括使用類型系統、條件檢查以及自定義類型等。
以下是一些常見的方法:
1. 使用類型系統限制參數類型
Kotlin的類型系統允許你通過參數類型限制參數可以接受的值。例如,如果只想接受某些枚舉值作為參數,可以使用枚舉類型。
enum class Color {
RED, GREEN, BLUE
}
fun setColor(color: Color) {
println("Color set to $color")
}
2. 使用泛型限定詞
可以通過泛型和限定詞(constraints)限制參數的取值類型。
fun <T : Number> printNumber(number: T) {
println("Number: $number")
}
printNumber(10) // OK
printNumber(3.14) // OK
// printNumber("string") // Error
3. 使用條件檢查
在函數內部進行條件檢查,限制參數的值。
fun setPercentage(percentage: Int) {
require(percentage in 0..100) { "Percentage must be between 0 and 100" }
println("Percentage set to $percentage")
}
setPercentage(50) // OK
// setPercentage(150) // Throws IllegalArgumentException
4. 使用數據類或封裝類
可以使用數據類或封裝類來限制參數的取值範圍。
class Percentage private constructor(val value: Int) {
companion object {
fun of(value: Int): Percentage {
require(value in 0..100) { "Percentage must be between 0 and 100" }
return Percentage(value)
}
}
}
fun setPercentage(percentage: Percentage) {
println("Percentage set to ${percentage.value}")
}
setPercentage(Percentage.of(50)) // OK
// setPercentage(Percentage.of(150)) // Throws IllegalArgumentException
5. 使用密封類(Sealed Class)
Kotlin的密封類(sealed class)可以用於限制函數參數的一組可能的值。
sealed class Direction {
object North : Direction()
object South : Direction()
object East : Direction()
object West : Direction()
}
fun move(direction: Direction) {
when (direction) {
is Direction.North -> println("Moving North")
is Direction.South -> println("Moving South")
is Direction.East -> println("Moving East")
is Direction.West -> println("Moving West")
}
}
move(Direction.North) // OK
// move(SomeOtherDirection) // Compile-time error
6. 使用註解和校驗(需要額外庫支持)
雖然Kotlin標準庫並不提供這樣的註解支持,但可以通過第三方庫(例如 JSR 380 Bean Validation)來實現參數校驗。
import javax.validation.constraints.Max
import javax.validation.constraints.Min
import javax.validation.constraints.NotNull
data class Person(
@field:NotNull
@field:Min(0) @field:Max(150)
val age: Int
)
// Validation can be performed using a Validator from javax.validation
以上是Kotlin中實現參數取值範圍和取值類型限制的一些常見方法。根據實際需求和項目背景,可以選擇適合的方法。
歡迎關注我的公眾號AntDream查看更多精彩文章!