Below class does not compile, if I declare Functions as an object instead of class I can run the method fac using Functions.fac(3) . Does it make sense in scala to attempt to run a class like this ? How can the below code be modified so that it runs without changing to object instead of class ?
class Functions {
def fac(n : Int) = {
var r = 1;
for(i <- 1 to n) r = r * i;
r
}
def main(args:Array[String]) = {
Functions f = new Functions();
print(f.fac(3));
}
}
The most obvious problem in your code is that you have
Functions f = .... This is Java syntax, so in Scala you need it to sayval f: Functions = ...Second, Scala makes a larger distinction between static and non-static things than Java. In Scala, something that’s static (such as a
mainmethod) is declared in an object. So you should separate theobject(static) parts from theclassparts.Third, your
facfunction could be more simply written as(1 to n).product.Finally, you don’t need the semi-colons.