Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an object to a method in Scala

How can I pass the reference of an object to method in Scala? E.g. I want this to compile

object Constants {
  val constantA:Double = ???
}


def calc(numbers:Seq[Double], Constants) = ??? // does not compile
def calc(numbers:Seq[Double], constants:Constants) = ??? // does not compile

Of course I can just reference Constants without passing it through the argument list, but I would prefer to list pass all dependencies of the method explicitly as arguments.

like image 544
Raphael Roth Avatar asked Mar 13 '17 10:03

Raphael Roth


3 Answers

Constants is an object. You don't specify objects as parameter types for method parameters, you specify types as parameter types for method parameters:

def calc(numbers:Seq[Double], constants: Constants.type) = ???

Generally speaking, more precise types are good, but in this case, it might be overdoing it with an overly precise type, since there is exactly one instance of the type Constants.type, so you cannot ever pass anything other than the Constants object as an argument, which makes the whole idea of "parameterizing" rather pointless.

like image 102
Jörg W Mittag Avatar answered Nov 03 '22 02:11

Jörg W Mittag


You can use the Any type

def calc(numbers:Seq[Double], constants: Any) 

but this wouldn't allow you to access the constantA value. Alternatively you could define a trait with the constant and let you object implement that:

trait ConstantA {
  val constantA:Double
}

object Constant extends ConstantA {
  override val constantA:Double = 0.0
}

def calc(numbers:Seq[Double], constants: ConstantA) {
   ...
   // use constants.constantA
   println(constants.constantA)
   ...
}
like image 4
Harald Gliebe Avatar answered Nov 03 '22 00:11

Harald Gliebe


In addition to Jörg W Mittag's answer, you can create an interface:

trait IConstants {
  def constantA: Double
}

object Constants extends IConstants {
  val constantA: Double = ???
}

def calc(numbers:Seq[Double], constants: IConstants) = ???

Whether this is useful very much depends on your specific situation.

like image 3
Alexey Romanov Avatar answered Nov 03 '22 02:11

Alexey Romanov