Is there a way to initialize Scala objects without using the β€œnew”?

For example, see the following.

http://www.artima.com/pins1ed/functional-objects.html

The code is used

val oneHalf = new Rational(1, 2) 

Is there a way to do something like

 val oneHalf: Rational = 1/2 
+7
source share
2 answers

I would recommend using some other operator (say \ ) for your Rational literal, since / already defined in 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 
+7
source

I'm going to steal MissingFaktor's answer, but change it a bit.

 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 better than using a backslash, and more consistent, since you want to define all the usual numerical operators on Rational anyway:

 scala> 1.r / 2 res0: Rational = Rational(1,2) 
+5
source

All Articles