How to define a global function in scala? - scala

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

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._

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(...)
}
}

Related

Is it possible to automatically load an implicit def if included as a dependency (no importing)

I'm working on a commons library that includes a config library (https://github.com/kxbmap/configs).
This config library uses "kebab-case" when parsing configuration files by default and it can be overridden by an implicit def in scope.
However, I don't want to force that on the users of my commons library when they get access to the config library transitively.
So without me forcing users to import this implicit, like:
import CommonsConfig._
can I somehow override the naming strategy via an implicit that gets into scope by only including my commons library on the classpath. I'm guessing no but I just have to ask :)
So if not, is someone aware of another approach?
kxbmap/configs isn't that well documented to explain this.
Thanks!
Implicits work in compile time, so they cannot get magically present if something is included and then disappear if it isn't.
The closest thing would be something like:
main library
package my.library
// classes, traits, objects but no package object
extension
package my
package object library {
// implicits
}
user's code
import my.library._
however that would only work if there were no package object in main library, only one extension library could pull off this trick at once (Scala doesn't like more than one package object) and user would have to import everything available with a package, always.
In theory you could create a wrapper around all you deps, with your own configs:
final case class MyLibConfig(configsCfg: DerivationConfig)
object MyLibConfig {
implicit val default: MyLibConfig = ...
}
and then derive using this wrapper
def parseThings(args...)(implicit myLibConfig: MyLibConfig) = {
implicit val config: DerivationConfig = myLibConfig.config
// derivation
}
but in practice it would not work (parseThings would have to already know the target type or would need to have the already derived implicits passed). Unless you are up to writing your own derivation methods... avoid it.
Some way of making user just import all relevant stuff is the most maintainable strategy. E.g. you could pull off the same thing authors did and add type aliases for all types that you use, do the same for companion objects and finally put some implicits there:
package my
package object library {
type MyType = some.library.Type
val MyType = some.library.Type
implicit val derivationConfig: DerivationConfig = ...
}

How could a "global implicit class" be defined in Scala?

Considering that a implicit class "must be defined inside of another trait/class/object"1, how can a implicit conversion be defined globally?
The case is that I'd like to add a method to all Strings (or Lists) in my application, or at least to several packages of it.
One cannot add anything to the "global" scope, neither in Java, nor in Scala.
However, in Scala one can define package objects, which can contain methods that are used all over the package, and can be easily imported by the user.
This looks something like this: in the directory foo/bar/baz one creates a file called package.scala with the following content:
package foo.bar
package object baz {
implicit def incrediblyUsefulConversion(s: String) = ...
}
The user then can do the following in his code to activate the conversion:
import foo.bar.baz._
or maybe
import foo.bar.baz.incrediblyUsefulConversion
Of course, you can also use your own code in other packages, just like any other user.

Types defined in a package object aren't in scope

To avoid writing out a large type in several places in my code, I thought I'd shortcut it using a type declaration in a package object:
package pet
package object pet {
type Ops = ((Int,Int) => Int,String)
}
object Q extends App {
val ops = List[Ops](
((_+_),"+"),
((_-_),"-"),
((_*_),"*")
)
}
But it's saying that for val ops, Ops isn't found. I'm guessing I'm misunderstanding something, but after looking over several package object examples, I can't tell what. There are no errors in the package object itself, so I don't think that it's a problem with that.
When declaring a package object, you need to place it in the package "above". As it stands, you're declaring package object pet inside package pet, so that Ops is actually located at the path pet.pet.Ops.
In your case, you should just place the package object inside it's own file without any package declaration.
If you were to import pet.pet._ inside Q it would also work.
Each package is allowed to have one package object. Any definitions
placed in a package object are considered members of the package
itself.
As seen from here, the definitions are package specific (in this case pet.pet). So you need to import them for use.
You can try:
object Q extends App {
import pet.pet._
...

What does this import exactly mean in Scala?

I encountered the following in Scala code:
class MyClass {
...
val a = new A; import a._
}
What does exactly val a = new A; import a._ mean ?
It imports the methods and variables of the a object. So if you want to call a.foo(), you can just call foo() instead.
It means that all methods and variables of a object of A type are now available in this block (scope) without explicitly mentioning a. So if A has a bar() method you can now say:
bar()
instead of
a.bar()
but only within the scope where import is defined.
Let's explain this with something you should be familiar with:
println("Hello world")
The question is: why does that work? There's no object called println with an apply method, which is the usual explanation for code that looks like that. Well, as it happens, the above code is really doing this:
Predef.println("Hello world")
In other words, println is a method on the object scala.Predef. So, how can you use it like above? Well, like this:
import scala.Predef._
println("Hello world")
Importing the contents of a stable reference (ie, not a var or a def) will make its methods available without having to prefix them with reference..
It also makes any implicits defined inside it available, which is how the implicit conversions defined inside scala.Predef are made available as well -- Scala imports the contents of java.lang, scala and scala.Predef (in that order, so the latter ones override the earlier ones).

Use function without explicit import in Scala

I like Scala's sys.error function - but I want to distinguish two cases: internal errors (e.g. database problem) and user errors (invalid input).
I tried extending Scala - but it doesn't seem to work:
package scala
class UserException(msg: String) extends RuntimeException(msg)
package object err {
def internal(message: String): Nothing =
sys.error(message)
def usr(message: String): Nothing =
throw new UserException(message)
}
How should I define err.usr() to be able to use it without an explicit import?
You can't, only scala.Predef is imported by default and it's not user extensible in any useful way.
You could put these definitions on the package object of your package hierarchy. Then, everything on that package will see them without import.