鑑於以下類型的寫作宏:爲正整數
sealed trait PosIntCheckResult
case class LteZero(x: Int) extends PosIntCheckResult
case object NotConstant extends PosIntCheckResult
我試圖寫檢查給定Int
是宏大於0
import reflect.macros.Context
def getInt(c: Context)(value: c.Expr[Int]): Either[PosIntCheckResult, Int] = {
import c.universe._
value.tree match {
case Literal(Constant(x)) => if (x > 0) Right(x) else Left(LteZero(x))
case _ => Left(NotConstant)
}
}
但Any
顯示出來對於x
值:
Test.scala:29: type mismatch;
found : Any
required: Int
case Literal(Constant(x)) =>
if (x > 0) Right(x) else Left(LteZero(x))
我該如何獲得公司mpiler期望Int
而不是Any
?
除了文字,我幾乎看不到一個簡單的方法來檢查是否「Int」值是正值(例如'def foo(x:Int)=''在運行前難以檢查'x')。您可能想看看https://github.com/non/spire/blob/master/README.md – cchantep
這是一種非主題,但您可能對我的博客文章感興趣[here](https:// meta .plasm.us/posts/2013/10/03/natural-vampires /)爲基於宏觀的解決類似問題。 –
在scalatest論壇中有些相關的問題 - https://groups.google.com/forum/#!topic/scalatest-users/guIlCXHbgh8 –