Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 577
MainstreamDeveloper00 Avatar asked Dec 06 '25 08:12

MainstreamDeveloper00


1 Answers

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.

like image 115
Vladimir Matveev Avatar answered Dec 08 '25 01:12

Vladimir Matveev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!