本文首发于公众号“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查看更多精彩文章!