簡體   English   中英

為什么不支持高階函數中的注釋?

[英]Why are annotations in higher-order functions unsupported?

這是我在高階function 中使用自定義注釋時遇到的錯誤:

圖像錯誤

有沒有辦法在高階函數中使用注釋? 如果不是,那將是什么替代解決方案(除了使用枚舉)?

這是我的自定義注釋的樣子:

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
}

解決方法

有一個涉及功能接口的解決方法(請注意下面的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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM