【问题标题】:Can you print $ in Scala string interpolation? [duplicate]你可以在 Scala 字符串插值中打印 $ 吗? [复制]
【发布时间】:2020-02-20 21:06:50
【问题描述】:

在 Scala 中,我想用字符串插值打印某些商品的价格。是否可以通过插值显示 $ 字符? 这有效:

scala> println(s"It only costs ${3 + 4} dollars")
It only costs 7 dollars

那么为什么这不起作用?根据docs

,它仍然应该是 7 美元
scala> println(s"It only costs $${3 + 4}")
It only costs ${3 + 4}

【问题讨论】:

    标签: string scala string-interpolation


    【解决方案1】:

    您还需要第三个$ 来进行实际插值。以下应该有效:

     s"It only costs $$${3 + 4} dollars"
    

    前两个$s 用于输出中的$ 符号,第三个用于插值。这样看可能更容易:

     s"It only costs $$ ${3 + 4} dollars"
    

    【讨论】:

    • 有道理。谢谢你。只需添加更多 $
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多