One is able to define methods without paranthesis if they have no arguments. A special use-case is to use this to get values. Should I do this, or rather directly get the value?
So
class Complex(real: Double, imaginary: Double) {
def re = real
def im = imaginary
override def toString() =
"" + re + (if (im < 0) "" else "+") + im + "i"
}
or
class Complex(real: Double, imaginary: Double) {
val re = real
val im = imaginary
override def toString() =
"" + re + (if (im < 0) "" else "+") + im + "i"
}
You can put val
in front of the constructor arguments to make it a bit shorter, which is effectively the same as your second piece of code:
class Complex(val re: Double, val im: Double) {
override def toString() = "" + re + (if (im < 0) "" else "+") + im + "i"
}
Note that def
defines a method, while val
defines a final member variable. Since the return value of these two methods is fixed, there's not really a reason to make them methods. So, in this case, use val
instead of def
.
Even better: make it a case class:
case class Complex(re: Double, im: Double) {
override def toString() = "%f%+fi".format(re,im)
}
This gives you re
and im
as members, plus some additional perks, such as copy
:
val a = Complex(1,2)
val realA = a.copy(im = 0)
and unapply
:
def isImaginary(a: Complex) = a match {
case Complex(0, _) => true
case _ => false
}
def abs(a: Complex) = a match {
case Complex(re, im) => re*re + im*im
}
and also equals
, hashCode
, etc.