【问题标题】:Why are annotations in higher-order functions unsupported?为什么不支持高阶函数中的注释?
【发布时间】:2020-05-31 14:52:56
【问题描述】:

这是我在higher-order 函数中使用自定义注释时遇到的错误:

有没有办法在高阶函数中使用注解?如果不是,那将是什么替代解决方案(除了使用枚举)?

这是我的自定义注释的样子:

companion object {
   private const val PERMISSION_DENIED = 1
   private const val PROVIDER_DISABLED = 2
   private const val SUCCESS = 3

   @IntDef(PERMISSION_DENIED, PROVIDER_DISABLED, SUCCESS)
   @Retention(AnnotationRetention.SOURCE)
   annotation class PreconditionResult
}

【问题讨论】:

    标签: function kotlin higher-order-functions


    【解决方案1】:

    解决方法

    有一个涉及功能接口的解决方法(请注意下面的fun interface)。

    注意:不幸的是,在 kotlin 代码中定义的功能接口仅在即将发布的 1.4 版本之后才可用。您现在可以使用1.4-M1 对其进行测试。

    fun interface FulFilled {
        fun execute(@PreconditionResult fulFilled: Int): Unit
    }
    
    private fun checkPrecondition(context: Context, fulFilled: Fulfilled) {
    }
    
    checkPrecondition(context) { fulFilled -> println("Got $fulFilled")}
    

    可能的解决方案

    我不确定它是否能达到您的要求,但也可以从您的类型定义中删除参数名称:

    private fun checkPrecondition(context: String, callback: (@PreconditionResult Int) -> Unit) {
    

    您需要将注释的目标更改为类型:

        @Retention(AnnotationRetention.SOURCE)
        @Target(AnnotationTarget.TYPE)
        annotation class PreconditionResult
    

    【讨论】:

    • 非常感谢 Jakub,我将尝试使用功能接口。第二种解决方案部分有效,因为我只想传递@IntDef 中定义的允许常量之一,如果我传递未定义的一个,编译器不会警告我
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-11
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 2020-01-14
    • 2011-04-21
    相关资源
    最近更新 更多