Actually in Scala 3, this code does not compile:
trait Constraint {
inline def assert(value: Foo): Boolean
}
class AndConstraint(inline left: Constraint, inline right: Constraint) extends Constraint {
override inline def assert(value: Foo): Boolean = left.assert(value) && right.assert(value)
}
This restriction can lead to some issues, for example in metaprogramming when we use FromExpr to retrieve a value at compile-time.
Shouldn’t Dotty add support of inline for constructor parameters ?
Example
Here is the suggested behaviour:
- an inline parameter can’t be var
- the constructor isn’t inline itself (what would be an inline constructor ?)
- the generated getter is inline and is should behave like any other inline method:
scala.compileTime.constValue
trait Constraint {
inline def assert(value: Int): Boolean
}
class Positive extends Constraint {
override inline def assert(value: Int): Boolean = value > 0
}
class Lesser[V <: Int] extends Constraint {
override inline def assert(value: Int): Boolean = value < constValue[V]
}
//Each call of left or right will be replaced by the inlined value
class AndConstraint(inline left: Constraint, inline right: Constraint) extends Constraint {
override inline def assert(value: Int): Boolean = left.assert(value) && right.assert(value)
}
@main def test = {
inline val andConstraint: AndConstraint = AndConstraint(Positive, Lesser[3])
andConstraint.assert(8) //replaced by `false`
andConstraint.assert(2) //replaced by `true`
}