zunior zunior - 2 months ago 10
Scala Question

Importing Functions from Other Classes in Scala

Say for example I have

class foo{
def bar = 7
}

class qaz{
//Here I want to have something like: val foobar = bar
//What I don't want to have is val foobar = (new foo).bar
}


How canI achieve this?

Answer

You can use the companion object of foo to define bar.

Then you can simply import it in qaz:

// in foo.scala
object foo {
  def bar = 7
}
class foo {
  // whatever for foo class
}

// in qaz.scala
import mypackage.foo.bar
class qaz {
  val foobar = bar     // it works!
}