Wouldn't it be cool (not necessarily simple to implement) to be able to specify the constraints of a function's input and have them checked statically and guaranteed by the compiler, just like it does for null safety?
For example, that a number is within a certain range (more so than the fact that the number fits into a Short or Long), or a string isn't empty or matches a regex. Possibly more complex things would be that a list can't be empty, or that the parameters match certain predicates.
In some ways this is the logical next step in specifying the constraint that objects can't be null (specifying other constraints).
I feel like function bodies would be more focused on what they are actually meant to do, instead of verifying input validity.
In some ways this is basically a
contract
about the preconditions. There could even be an error message associated with each precondition.
@Precondition(
target=a,
condition=Preconditions.nonNegative(),
message="a cannot be negative!"
)
@Precondition(
target=a, condition=Preconditions.lessThan(b),
message="a must be less than b!"
)
fun foo(a: Int, b: Int)
Could also apply to variables:
@Invariant(condition=Preconditions.nonNegative())
@Invariant(condition=Preconditions.inRange(1..5)
var x: Int
Could possibly do
@Invariant(conditions=[...])