Arguments to Objects

Arguments to Objects
0.0 0


Can arguments be passed to objects in Scala?


Objects do not have arguments.They are singleton classes.They cannot be hence passed with arguments when an instance of it is created.
However,if you create a case class,then a companion object is created along-with it.In such a case an instance of the object can be created while passing arguments to the object.


Thanks for reply. I am very new to Scala , hence this basic question.

I was reffering below code from itversity example. here while running this object - “combination” , 2 arguments were passed. Could you please help me in understanding this.

object combination {
def nCr(n: Int, r: Int) = {
def fact(i: Int) = {
var res = 1
for(e <- i to 1 by -1)
res = res * e

fact(n)/(fact(n-r) * fact(r))


def main(args: Array[String]): Unit = {
val n = args(0).toInt
val r = args(1).toInt
val c = nCr(n, r)
println(“There are " + c + " combinations of " + r + " in " + n + " elements”)



If you refer to this example,then we have provided those arguments to the main function and not the object.
We have provided those under ‘edit configurations’: program arguments.
These arguments will then go to args(0) and args(1).

You will get the concept of passing arguments to the objects once you study case classes.


Thank you for explanation.