Scala中的类型安全格式化输出

Mic*_*ael 3 printf scala

我在想是否可以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

win*_*ner 5

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)

  • 这看起来更像是一个评论 - 它并没有真正尝试回答这个问题. (3认同)