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 } }
ct
はBoolean
ではなく、true
のためだけの型Boolean(true)
となる。
言語仕様により、THREE
にtype-annotationをつける(THREE: Int
にする)とconstantではなくなるので注意。