【问题标题】:How can I use annotation @IntRange for Kotlin extension function for Integer如何将注释 @IntRange 用于 Integer 的 Kotlin 扩展功能
【发布时间】:2022-01-06 12:36:35
【问题描述】:

下面是我的 Kotlin 扩展函数:

infix fun Int.send(data: String) {
    MsgSendUtils.sendStringMsg(
        this,
        data
    )
}

这样称呼:

 8401 send "hi"

我的要求是: 调用者必须大于 8400 。

我怎样才能做到这一点?

谢谢!

【问题讨论】:

    标签: kotlin annotations extension-function


    【解决方案1】:

    理论上,您可以使用语法@receiver:IntRange(from = 8400) 将注解应用于函数的接收者:

    infix fun @receiver:IntRange(from = 8400) Int.send(data: String) {
        MsgSendUtils.sendStringMsg(this, data)
    }
    

    但是,这似乎不会像您预期的那样触发 Android Lint 错误。在检查 Kotlin 代码时,这可能是 linter 本身缺少的功能。

    一种解决方法是用不同的方式声明函数(使用这个值作为参数而不是接收器):

    fun send(@IntRange(from = 8400) id: Int, data: String) {
        MsgSendUtils.sendStringMsg(id, data)
    }
    // or
    fun String.sendTo(@IntRange(from = 8400) id: Int) {
        MsgSendUtils.sendStringMsg(id, this)
    }
    

    否则,您可以在纯 Kotlin 中做的最好的事情是在运行时检查值:

    infix fun Int.send(data: String) {
        require(this >= 8400) { "This value must be greater than 8400" }
        MsgSendUtils.sendStringMsg(this, data)
    }
    

    请注意,根据此值所代表的含义,我建议使用更具体的类型而不是 Int。例如,如果您的 Int 代表一个 ID,也许您应该声明一个包装此整数的 value class。然后,您可以在构建时强制执行约束(仍在运行时,但它不太容易出错)。

    这种方法还可以避免污染所有整数的自动完成,考虑到这个功能的具体程度,这在大型项目中可能会非常烦人。

    【讨论】:

      猜你喜欢
      • 2018-10-11
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 2020-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多