Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 4.0

First write a Scala class:

Code Block
titleComplex.scala
class Complex(real: double, imaginary: double) {
  def re = real
  def im = imaginary
  override def toString() = "" + re + (if (im < 0) "" else "+") + im + "i"
}

Compile this using scalac:

Code Block
none
none
> scalac Complex.scala

Now write our Groovy Program:

Code Block
titleComplexMain.groovy
println new Complex(1.2, 3.4)

Now run the program (assuming scala-library.jar is in the CLASSPATH):

Code Block
none
none
> groovy ComplexMain

Which produces:

No Format
1.2+3.4i

Note that in this example it would have been just as easy to write our Complex class using Groovy as follows:

Code Block
class Complex {
  def re, im
  Complex (double real, double imaginary) {
    re = real
    im = imaginary
  }
  String toString() { "$re" + (im<0 ? '' : '+') + im + 'i' }
}

but in other cases you may have some existing Scala classes you wish to reuse from Groovy.