我在想是否可以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?
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"
^
Run Code Online (Sandbox Code Playgroud)