PS

ConstantType

ConstantType

Scalaには7.typeのような型(constant type)がこっそり含まれていた。macroで取り出して使うことができる。

object ConstantTypeOf {
    type apply[T](x: T) = macro impl[T]

    def impl[T: c.WeakTypeTag](c: Context)(x: c.Expr[T]): c.Tree = {
        import c.universe._

        x.tree match {
            case Literal(c @ Constant(_)) => TypeTree(ConstantType(c))
            case t => c.abort(c.enclosingPosition, "not constant: " + show(t))
        }
    }
}

簡単な演算はconstantになるらしい。

    final val THREE = 3

    def testSmart {
        type ct = ConstantTypeOf.apply(1+2 == THREE)
        val x: ct = true

        Test.expectError {
            val x: ct = false
        }
    }

ctBooleanではなく、trueのためだけの型Boolean(true)となる。

言語仕様により、THREEにtype-annotationをつける(THREE: Intにする)とconstantではなくなるので注意。

参考文献