1

I'm using play framework, I want to define a global function, How can I do it?

First I define the function in SomeFunc.scala and import it to every file which I will use it.

Is it possible to direct use it like println without import SomeFunc.scala

Sato
  • 8,192
  • 17
  • 60
  • 115

2 Answers2

3

println is defined in the object scala.Predef. The members of which is always in scope, there is no way you can add to that, but as the question linked to by senia says you can achieve sort of the same by defining a method in a package object which will then be available inside code in that package.

Another solution that some libraries uses is to provide an Imports object with aliases and shortcuts just like Predef, but that you have to explicitly import with a wildcard. For example nscala-time does this:

import com.github.nscala_time.time.Implicits._
johanandren
  • 11,249
  • 1
  • 25
  • 30
2

Yes it is possible, but only global in the same package, not absolute global.

package com
package object myproject {
  def myGlobalFunc(..) = ...
}

Then you use it like this:

package com.myproject 
object HelloWorld {
  def main(args: Array[String]) {
    myGlobalFunc(...)
  }
}
tabdulradi
  • 7,456
  • 1
  • 22
  • 32