For example see the following
http://www.artima.com/pins1ed/functional-objects.html
The code uses
val oneHalf = new Rational(1, 2)
Is there a way to do s开发者_如何学编程omething like
val oneHalf: Rational = 1/2
I would recommend using some other operator (say \
) for your Rational
literal, as /
is already defined on all numeric types as a division operation.
scala> case class Rational(num: Int, den: Int) {
| override def toString = num + " \\ " + den
| }
defined class Rational
scala> implicit def rationalLiteral(num: Int) = new {
| def \(den: Int) = Rational(num, den)
| }
rationalLiteral: (num: Int)java.lang.Object{def \(den: Int): Rational}
scala> val oneHalf = 1 \ 2
oneHalf: Rational = 1 \ 2
I'm going to steal MissingFaktor's answer, but change it up slightly.
case class Rational(num: Int, den: Int) {
def /(d2: Int) = Rational(num, den * d2)
}
object Rational {
implicit def rationalWhole(num: Int) = new {
def r = Rational(num, 1)
}
}
Then you can do something like this, which I think is a little nicer than using the backslash, and more consistent since you'll want to define all the usual numeric operators on Rational anyway:
scala> 1.r / 2
res0: Rational = Rational(1,2)
精彩评论