4

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?

zunior
  • 841
  • 2
  • 13
  • 24

2 Answers2

9

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!
}
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118
  • For this to work, foo would need to be the companion object of foo.scala ? Can I have a companion class as well? – zunior Jul 16 '14 at 15:35
2

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.

Community
  • 1
  • 1
ameenkhan07
  • 35
  • 1
  • 5