我在考虑是否有可能printf
在Scala中实现类型安全。假设我们只需要支持字符串文字,%s和%d
我想printf("This is number %d", 0)
编译但printf("This is number %d", "abc")
不希望被编译。
我想printf
检查编译时参数的数量。因此printf("This is a literal")
将被编译,但printf("This is number %d and string %s", 0)
不会。
我已经知道可以使用宏完成此操作。宏对于实现类型安全是否绝对必要printf
?
这是尝试在没有宏的情况下实现这样的事情。可能没有那么丑陋的方法了……应该添加一些额外的方法以使其更加方便。
import scala.language.implicitConversions
package test {
sealed trait End
sealed trait Prove[T]
object Prove{
implicit object EndProve extends Prove[F[End,End]]
}
class F[A,B](ss: List[String]){
def _d(s: String) = new F[Int,F[A,B]](s :: ss)
def _s(s: String) = new F[String,F[A,B]](s :: ss)
}
}
package object test {
implicit def string2F(s: String) = new F[End,End](List(s))
def printf[A,B](a: A)(f: F[A,B])(implicit ev: Prove[B]) = ???
def printf[A,B,C](b: B, a: A)(f: F[A,F[B,C]])(implicit ev: Prove[C]) = ???
def printf[A,B,C,D](c: C, b: B, a: A)(f: F[A,F[B,F[C,D]]])(implicit ev: Prove[D]) = ???
// and so on...
}
如您所见,它确实有效(如果您执行实际的打印):
scala> import test._
import test._
scala> printf(4, "string")("a digit: " _d " and a String: " _s ".") // compiles
scala.NotImplementedError: an implementation is missing
scala> printf(4, 6)("a digit: " _d " and a String: " _s ".") // doesn't compile
<console>:11: error: type mismatch;
scala> printf(4)("a digit: " _d " and a String: " _s ".") // doesn't compile
<console>:11: error: type mismatch;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句