https://kotlinlang.org logo
g

Geert

11/12/2020, 1:35 PM
I’m trying to add a property to an interface with a default value, that is no problem. But thats a function,  and I need a property that can change Why isn’t contracts supported for properties? This is my code:
Copy code
interface PrimitiveType<T> {
    var value: T?
}

interface Defaultable<T> {
    var defaultValue: T
}

@ExperimentalContracts
fun <T> PrimitiveType<T>.defaultValue() : T {
    contract {
        returns() implies ( this@defaultValue is Defaultable<*>)
    }

    return this.value!!
}


@ExperimentalContracts
fun <T> PrimitiveType<T>.editValue() : T {
    contract {
        returns() implies ( this@editValue is Defaultable<*>)
    }

    return this.value!!
}

@ExperimentalContracts
fun <T> PrimitiveType<T>.setEditValue(value: T) {
    contract {
        returns() implies ( this@setEditValue is Defaultable<*>)
    }

    this.value = value
}
d

dmitriy.novozhilov

11/12/2020, 3:34 PM
First of all, contracts in your example are unsafe: since
value
declared as
var
in interface compiler won't provide smartcasts for it for two reasons: 1. It is
var
, so in any time other thread may change value to
null
(for example) and smartcast would not be valid 2. It is property declared in interface, so real implementation may be declared as
get()
which returns random value for each access And for contracts on properties: currently contracts in getters and setters are unsupported due to problems with their implementation in current compiler frontend (aka FE 1.0) We are going to introduce redesigned contracts with new features and syntax in new compiler (aka Frontend IR, aka FIR), and contracts for properties will work There is no plans to work on contracts in FE 1.0, because we focus all our resources to complete FIR so unfortunately those changes won't be available for year or even more