我在想是否可以在 Scala 中实现类型安全的 printf
。假设我们只需要支持字符串文字、%s和%d
我希望编译 printf("This is number %d", 0)
但 printf("This is number %d", "abc")
不是。
我希望 printf
检查编译时的参数数量。因此 printf("This is aliteral")
会被编译,但 printf("This is number %d and string %s", 0)
不会。
我已经看到可以用宏来完成。宏对于实现类型安全 printf
是绝对必要的吗?
最佳答案
Scala 的 f
字符串格式化程序已经是类型安全的 printf
。它是使用宏来实现的。示例:
scala> val s = "not a number"
s: String = not a number
scala> f"$s%d"
<console>:9: error: type mismatch;
found : String
required: Int
f"$s%d"
^
关于scala - Scala 中类型安全的格式化输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24470214/