Get value directly or through a method in Scala?

One of them can 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, get 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"
}
0
source share
2 answers

You can prefix the valconstructor arguments to make it a little shorter, which actually matches your second piece of code:

class Complex(val re: Double, val im: Double) {
  override def toString() = "" + re + (if (im < 0) "" else "+") + im + "i"
}

, def , val -. , . , val def.

+2

: :

case class Complex(re: Double, im: Double) {
   override def toString() = "%f%+fi".format(re,im)
}

re im , , copy:

val a = Complex(1,2)
val realA = a.copy(im = 0)

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
}

equals, hashCode ..

+1

Source: https://habr.com/ru/post/1656696/


All Articles