zunior zunior - 1 year ago 99
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 Source

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!
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download