I have a question about Kotlin contracts. As a lib...
# announcements
c
I have a question about Kotlin contracts. As a library creator, how can I define functions that leverage contracts without forcing the users to use
OptIn
annotation or compiler flags? Should I annotate my methods/files with
@OptIn(ExperimentalContracts::class)
?
a
You can suggest your user to add compiler options to avoid need to use this annotation.
Copy code
compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
    kotlinOptions {
        freeCompilerArgs = ["-Xopt-in=kotlin.contracts.ExperimentalContracts"]
    }
}
So that user can use specify this once for opt-in change in whole project.
c
I know that's an option, but I'd rather avoid that, as this would immediately become mandatory for some of my libraries. I'd like to keep the setup minimal for the users - especially since even if the contracts API would change, the public API of my libraries will remain the same. I'll only have to modify the internal definitions of the contracts.
a
You have to let user know about your api is using experimental api and can fail anytime soon if eversince there is some large changes. IIRC there's no way to hide these type of experimental suggesstion/error that pops up.
c
I mean,
OptIn
seems to do exactly that. Notice how stdlib utilities such as
apply
or
let
use contracts, but do not propagate the warnings. Since there are no major changes planned in 1.4 (at least in the parts of the contracts that I'm using), I think I prefer ease of setup over excessive warnings and "what-if" situations.
z
The implementation of contracts has already been stable for some time, so you should be able to use them in your library's functions without impacts on future binary compatibility. The syntax used to define the contracts is experimental, but that won't affect your consumers unless they're building your library from source.
c
@Zach Klippenstein (he/him) [MOD] That's what I've been thinking. Even if the contracts API changes, this will mostly affect the library itself, not the users' projects. And besides, contracts are stripped in the compiled code AFAIK either way. I went with
@OptIn(ExpertimentalContracts::class)
, making the contracts usage easy for the library users - they do not have to use any annotations or compiler flags. Thanks for your input guys.
d
I can approve that we don't break binary compatibility for existing contracts at least in few further major releases (and, probably never), but there is a very big possibility that contrat syntax will be greatly changed in new compiler, that was announced at KotlinConf 19.