Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to initialise Scala objects without using "new"?

Tags:

scala

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 something like

val oneHalf: Rational = 1/2
like image 705
deltanovember Avatar asked Jul 09 '11 02:07

deltanovember


2 Answers

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
like image 66
missingfaktor Avatar answered Nov 04 '22 01:11

missingfaktor


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)
like image 25
Kris Nuttycombe Avatar answered Nov 03 '22 23:11

Kris Nuttycombe