Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 584
zunior Avatar asked Aug 31 '25 05:08

zunior


1 Answers

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!
}
like image 194
Jean Logeart Avatar answered Sep 03 '25 15:09

Jean Logeart