Can I define and use functions outside classes and objects in Scala?

MainstreamDeveloper00 picture MainstreamDeveloper00 · Aug 31, 2013 · Viewed 9.9k times · Source

I begin to learn Scala and I'm interesting can I define and use function without any class or object in Scala as in Haskell where there is no OOP concept. I'm interested can I use Scala totally without any OOP concept?

P.S. I use IntelliJ plugin for Scala

Answer

Vladimir Matveev picture Vladimir Matveev · Sep 1, 2013

Well, you cannot do that really, but you can get very close to that by using package objects:

src/main/scala/yourpackage/package.scala:

package object yourpackage {
  def function(x: Int) = x*x
}

src/main/scala/yourpackage/Other.scala:

package yourpackage

object Other {
  def main(args: Array[String]) {
    println(function(10));   // Prints 100
  }
}

Note how function is used in Other object - without any qualifiers. Here function belongs to a package, not to some specific object/class.