Kotlin - Why do compiler contracts only allow references to function parameters

975 Views Asked by At

When writing validation function, often times these validation functions check for nullability. Even though, after calling these functions an objects members can be safely used as if they were non-nullable, Kotlin compiler contracts don't allow specifying this behavior.

For instance:

data class EmployeeDto(
  val name: String?,
  val longitude: String?,
  val latitude: String?
) {
  @ExperimentalContracts
  fun validate() {
    //contract { returns() implies (this.name != null && this.longitude != null && this.latitude != null) }
    // Error in contract description: only references to parameters are allowed in contract description

    if (name.isNullOrEmpty())
      throw RequiredValueNotSetException("Name was set to \"$name\" but can not be null or empty")
    if (longitude.isNullOrEmpty())
      throw RequiredValueNotSetException("Longitude was set to \"$longitude\" but can not be null or empty")
    if (latitude.isNullOrEmpty())
      throw RequiredValueNotSetException("Latitude was set to \"$latitude\" but can not be null or empty")
  }

What is the rationale behind this constraint or is this is a feature planned to be added in the future?

1

There are 1 best solutions below

0
On BEST ANSWER

What is the rationale behind this constraint?

Kotlin contracts are an experimental feature both in design and implementation. A lot of constraints are simply there because it is easier/faster to implement contracts with those constraints.

is this is a feature planned to be added in the future?

It is likely that the constraint of only referencing method parameters will be lifted in the future.

It is hard to say what will happen with kotlin contracts, as there isn't really any official roadmap for contracts aside from what is in the KEEP and corresponding discussion. In the comments of this post a kotlin team member mentioned some contract improvements will come after the new compiler frontend, which itself is still on the roadmap.