As the other answers have indicated, its not possible to define a function without an object or class, because in Scala, functions are objects and (for example) Function1
is a class.
However, it is possible to define a function without an enclosing class or object. You do this by making the function itself the object.
src/main/scala/foo/bar/square.scala
:
package foo.bar
object square extends (Int => Int) {
def apply(x: Int): Int = x * x
}
extends (Int => Int)
is here just syntactic sugar for extends Function1[Int, Int]
.
This can then be imported and used like so:
src/main/scala/somepackage/App.scala
:
package foo.bar.somepackage
import foo.bar.square
object App {
def main(args: Array[String]): Unit = {
println(square(2)) // prints "4"
}
}