RequiresOptIn for property access?

Hi,

I’m new to Kotlin and absolutely loving it. Just dropping in to ask if there are plans to have the @RequiresOptIn work with property accessors. Do you see value in being able to mark a property as experimental, for example?

Thanks,
David

1 Like

You can currently mark a property as experimental/requires opt-in, but you need to place an annotation right on the property itself, not on its accessors, for example:

@ExperimentalStdlibApi
val experimentalProperty: String get() = ...

Annotating individual accessors is not yet supported enough, you can follow KT-45227 for updates on that.

2 Likes

Hey, that’s great! I was trying to figure out why I thought this didn’t work, and it’s because I was annotating a property declared in the constructor. This does not produce an opt-in requirement in Kotlin 1.4.30:

class Foo(
    @ExperimentalStdlibApi
    val experimentalProperty: String
)

fun main() {
    // no opt-in warning
    println(Foo("bar").experimentalProperty)
}

The workaround is easy enough:

@Suppress("CanBePrimaryConstructorProperty")
class Foo(experimentalProperty: String) {
    @ExperimentalStdlibApi
    val experimentalProperty: String = experimentalProperty
}

Thanks,
David

Ah, yes, the problem in this case is that the annotation is sticking to the constructor parameter rather than to the property. It can be targeted to the corresponding property though by specifying an explicit annotation target:

class Foo(
    @property:ExperimentalStdlibApi
    val experimentalProperty: String
)
2 Likes

I agree that this situation is far from convenient. This usability problem is tracked as KT-41055

1 Like