开发者

In Scala, is there a way to represent price as $Y.YY?

At the moment, I'm开发者_如何学JAVA thinking of representing price as follows:

case class Price(amount: Double)

Which allows me to do

val price = Price(4.52)

Is there any mechanism which would allow me to create a Price object as follows?

val price = $4.52


No because $4 is a valid identifier and . signifies a method.

However you could say

val $ = Price 

to set $ equal to the price companion object and parenthetize the Double:

scala> val p = $(4.52)
p: Price = Price(4.52)

edit: another thing you could do would be:

scala> implicit def toDollar(d: Double) = new {
     |   def $ = Price(d)
     | }
toDollar: (d: Double)java.lang.Object{def $: Price}

scala> val p = 4.52 $
p: Price = Price(4.52)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜