zunior
zunior

Reputation: 861

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?

Upvotes: 4

Views: 8836

Answers (2)

ameenkhan07
ameenkhan07

Reputation: 35

There are 2 ways to achieve this:

  1. Using a Companion Object

  2. Case Class

The second method, i.e. method requiring the inclusion of a companion object, as already implemented by Jean :

class foo {
// whatever for foo class
}

//Companion Object
object foo {
    def bar = 7
}

class qaz {
  val foobar = bar 
}

By creating a case class instead of a normal class, a lot of boilerplate code is created for you, one of which is generation of an apply method, so you don’t need to use the new keyword to create a new instance of the class.

case class foo{
  def bar = 7
}

class qaz{
   val foobar = bar  
}

Both of these approaches are sort of syntactic sugar but doing the same thing in the back, that is, using an apply function in a companion object. Try this for more information.

Upvotes: 2

Jean Logeart
Jean Logeart

Reputation: 53819

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!
}

Upvotes: 9

Related Questions