-
Notifications
You must be signed in to change notification settings - Fork 4.2k
Description
Traits
Traits are a specification a Type / Method must have to be valid. This specification is validation at both compile-time and runtime. The runtime cost maybe worth it for additional safety,
Basic Grammar
trait ::= "Trait" identifier specification
specification ::= '{' spec+ '}'
spec ::=
incomplete
A trait can be define in a separate construct, like a class / struct.
Examples
trait Zero { static readonly Zero ()->T }
trait Unit { static readonly Unit ()->T }
trait [+] ( static [+] (T,T)->T } // operator + (addition)
trait [-] { static [-] (T,T)->T } // operator - (subtraction)
A trait can "inherit" other existing traits. eg.
trait SimpleCalc <: { Zero, Unit, [+], [-] }
This allows "constrained generics" over numeric types.
Summation< T > ( IEnumerable<T> nums )
T has SimpleCalc
{
T total = T.Zero();
foreach( T num in nums)
total = total + num; // += can't be used as the specification didn't specify it.
return total;
}
A trait can also be anonymously define at the point of use
foo <T> ()
T has Trait { ... }
{
// method code
}
Value Traits
Value Trait are checked against the value of a variable, if it possible to valid at compile-time it is, if not it is validated at runtime.
trait NonNull <T : class> { != null }
int CharCount ( string s )
s is NonNull
{
return s.Length;
}
Note: T! could be an alias for the NonNull Trait
I do require help to spec-out this idea, I think it has potential has *(as see it) that traits would also enable other current proposals / part of them.
- NonNull C# Design Notes for Jan 21, 2015 #98
- Method Contracts Proposal: Method Contracts #119
- Constraints aspect of Constrained primitive and string types #104