【问题标题】:Create Custom Dagger 2 Scope with Kotlin使用 Kotlin 创建自定义 Dagger 2 范围
【发布时间】:2018-06-10 22:27:27
【问题描述】:

我正在尝试将 Java 代码转换为 Kotlin 以创建自定义匕首范围。

这是Java代码:

@Documented
@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomScope {
}

这里转换成kotlin就是结果

@Scope
@Documented
@Retention(RetentionPolicy.RUNTIME) annotation class CustomScope 

我的类型与 @Retention(RetentionPolicy.RUNTIME) 不匹配。我收到以下错误消息:Required Type is AnnotationRetention but RetentionPolicy type was found.

@interface 似乎也被替换了。

【问题讨论】:

    标签: java android kotlin dagger-2


    【解决方案1】:

    您可能使用的 Retention 注释类来自 Kotlin 的库(来自包 kotlin.annotation)。

    它需要一个枚举类型AnnotationRetention 的属性。所以,你可以这样做:

    @MustBeDocumented
    @Scope
    @Retention(AnnotationRetention.RUNTIME)
    annotation class CustomScope
    

    顺便说一句,如果您查看Annotations.kt 文件,您会看到Retention 注释在您不向其传递任何内容时将采用默认属性AnnotationRetention.RUNTIME

    所以,只需 @Retention 注释也可以。

    【讨论】:

    • 另请注意,注释应按以下顺序排列:MustBeDocumented、Scope & Retention(AnnotationRetention.RUNTIME) 以外的顺序,范围界定将不起作用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-07
    相关资源
    最近更新 更多