简体   繁体   中英

enforce Resource Annotation for implementation of abstract val

I have a class with an abstract value that is annotated with @StringRes:

@get: StringRes
abstract val foo : Int

Unfortunately when I pass a non StringRes to that value in the implementation like this:

override val foo = 2

it still compiles fine - but I want it to throw a compile time error.

The only workaround I found so far is using a function instead of a val - so this fails fine at compile time:

@StringRes
abstract fun bar() : Int

and

override fun bar() = 1

But I would like to use a val in this case. Anyone knows how to do it with a val?

@get is property getter, so when you will use Kotlin's property getter:

var <propertyName>[: <PropertyType>] [= <property_initializer>]
    [<getter>]
    [<setter>] 

like so:

abstract class Hello {
    @get :StringRes
    abstract val foo: Int
}

class World : Hello() {
    override val foo: Int
        get() = 123
}

it will generate compile time error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM