I was thinking about custom constraints at languag...
# language-evolution
p
I was thinking about custom constraints at language level:
Copy code
constraint<String> NotEmpty {
  fun validate(v: String) {
    if (v.isEmpty()) {
  	  throw ConstraintValidationException("Empty string")		
    }
  }
}

constraint<String> NoSpace {
  fun validate(v: String) {
    if (v.contains(' ') {
	  throw ConstraintValidationException("Spaces in string")		
    }
  }
}

typealias SeveralConstraints = NotEmpty | NoSpace


fun test(str: @NotEmpty String) {
   ....	
}

fun test2(str: @SeveralConstraints String) {
   test(str) // no generated code fo validation because str already validated for NotEmpty that is included in SeveralConstraints 		
}

fun test3(str: @NotEmpty String) {
   test(str) // no generated code fo validation because str already validated
   test2(str) // compiler generates code for validation NoSpace, NotEmpty is already validated	
}
y
youtrack.jetbrains.com/issue/KT-51417/Restricted-types github.com/Kotlin/KEEP/blob/…/0006-refinement-types.md although your case is mildly different because it's adding runtime checks, so maybe an explicit cast could do the trick?
Copy code
fun test3(str: @NotEmpty String) {
   test(str) // no generated code fo validation because str already validated
   test2(str as (@SeveralConstraints String)) // compiler generates code for validation NoSpace, NotEmpty is already validated	
}
p
Explicit cast even better!
s
Just to confirm my understanding: an inline value class is a lesser solution here due to the lack of polymorphism/smartcasting with the underlying type? (and also that several refinements are needed)
y
Yes, but also some syntactic sugar for
is
and
as
would be nice! I.e.
is
checking the underlying condition, and
as
throwing an error if the condition doesn't match