What does this import exactly mean in Scala? - 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).

Related

How come "println" without being enclosed in a method, allowed inside a scala class?

I'm new to Scala and in Scala I found that one can write println directly inside a class despite it not being a variable or method, how is this possible?
Even if println is a method then why aren't we defining it in the class as required generally for methods? Why despite being a method it is not allowed directly in Java class but allowed in Scala?
E.g.
class Hero {
println("running fine...") // Why is this println allowed in scala when its not inside a function?
}
object MainObject{
def main(args: Array[String]){
new Hero()
}
}
Basically, it runs inside the Class constructor. Any code inside the Class besides the variable and function declarations is constructor's code.
You can write any statement directly inside a class and it will be run whenever the class is instantiated.
When you open up an editor and start typing code, you will find, that some things are already available and some need to be imported. So all of these things which are available without importing are present in the scala.Predef package.
println is one of the methods made available by the scala compiler in the scala.Predef package.
def println() = Console.println()
If you check the scala docs, println method internally calls the Console object to print the contents on the screen.
I'm new to Scala and in Scala I found that one can write println directly inside a class despite it not being a variable or method, how is this possible?
You are wrong: println is a method, that's why this is possible. Here is the documentation for scala.Predef.println.

Calling type-specific code from a library function, determined at compile-time

How can you make code in a Scala library call type-specific code for objects supplied by a caller to that library, where the decision about which type-specific code to call is made at compile-time (statically), not at run-time?
To illustrate the concept, suppose I want to make a library function that prints objects one way if there's a CanMakeDetailedString defined for them, or just as .toString if not. See nicePrint in this example code:
import scala.language.implicitConversions
trait CanMakeDetailedString[A] extends (A => String)
def noDetailedString[A] = new CanMakeDetailedString[A] {
def apply(a: A) = a.toString
}
object Util {
def nicePrint[A](a: A)
(implicit toDetail: CanMakeDetailedString[A] = noDetailedString[A])
: Unit = println(toDetail(a))
def doStuff[A](a: A)
: Unit = { /* stuff goes here */ nicePrint(a) }
}
Now here is some test code:
object Main {
import Util._
case class Rototiller(name: String)
implicit val rototillerDetail = new CanMakeDetailedString[Rototiller] {
def apply(r: Rototiller) = s"The rototiller named ${r.name}."
}
val r = Rototiller("R51")
nicePrint(r)
doStuff(r)
}
Here's the output in Scala 2.11.2:
The rototiller named R51.
Rototiller(R51)
When I call nicePrint from the same scope where rototillerDetail is defined, the Scala compiler finds rototillerDetail and passes it implicitly to nicePrint. But when, from the same scope, I call a function in a different scope (doStuff) that calls nicePrint, the Scala compiler doesn't find rototillerDetail.
No doubt there are good reasons for that. I'm wondering, though, how can I tell the Scala compiler "If an object of the needed type exists, use it!"?
I can think of two workarounds, neither of which is satisfactory:
Supply an implicit toDetail argument to doStuff. This works, but it requires me to add an implicit toDetail argument to every function that might, somewhere lower in the call stack, have a use for a CanMakeDetailedString object. That is going to massively clutter my code.
Scrap the implicit approach altogether and do this in object-oriented style, making Rototiller inherit from CanMakeDetailedString by overriding a special new method like .toDetail.
Is there some technique, trick, or command-line switch that could enable the Scala compiler to statically resolve the right implicit object? (Rather than figuring it out dynamically, when the program is running, as in the object-oriented approach.) If not, this seems like a serious limitation on how much use library code can make of "typeclasses" or implicit arguments. In other words, what's a good way to do what I've done badly above?
Clarification: I'm not asking how this can be done with implicit val. I'm asking how you can get the Scala compiler to statically choose type-appropriate functions in library code, without explicitly listing, in every library function, an implicit argument for every function that might get called lower in the stack. It doesn't matter to me if it's done with implicits or anything else. I just want to know how to write generic code that chooses type-specific functions appropriately at compile-time.
implicits are resolved at compile time so it can't know what A is in doStuff without more information.
That information can be provided through an extra implicit parameter or a base type / interface as you suggested.
You could also use reflection on the A type, use the getType that returns the child type, cast the object to that type, and call a predefined function that has the name of the type that writes the string details for you. I don't really recommend it as any OOP or FP solution is better IMHO.

How to (properly) enrich the standard library?

I would like to define an implicit conversion from Iterator[T] to a class that I have defined: ProactiveIterator[A].
The question isn't really how to do it but how to do it properly, i.e. where to place the method, so that it is as transparent and unobtrusive as possible. Ideally it should be as the implicit conversion from String to StringOps in scala.Predef If the conversion was from a class in the library to some other class, then it could be defined inside that class, but AFAIK that's not possible here.
So far I have considered to add an object containing these conversions, similarly to JavaConversions, but better options may be possible.
You don't really have much of a choice. All implicits must be contained within some sort of object, and imported with a wildcard import (you could import them individually, but I doubt you want that).
So you'll have some sort of implicits object:
package foo.bar
object Implicits {
implicit class ProactiveIterator[A](i: Iterator[A]) {
...
}
}
Then you must explicitly import it wherever you use it:
import foo.bar.Implicits._
In my opinion, this is a good thing. Someone reading the code might not understand where your pimped methods are coming from, so the explicit import is very helpful.
You can similarly place your implicits within a package object. You would have to import them the same way into other namespaces, but they would be available to classes within the same package.
For example, using the following, anything within foo.bar will have this implicit class available:
package foo
package object bar {
implicit class ProactiveIterator[A](i: Iterator[A]) {
...
}
}
Elsewhere you would import foo.bar._ (which may or may not be as clean, depending on what's in bar).

How to define a global function in 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(...)
}
}

object field import in scala

I have a very simple question of style.
What is the best way to access a field or a method defined in an object ?
For example if I have an object Foo that define a field bar, would you rather do import Foob.bar and then refer to it in the scope as bar or call Foo.bar wherever you need the field. From what I have read in most libraries, Foo.bar seems the standard way to do it but I would like to be sure.
Thanks,
Yeah, usually Foo.bar is used, but that depends on the coder community behind the project as Frank pinted out.
If you would like to use all members without having to prefix it with Foo, you can do that too:
object Foo {
val x = "..."
}
class Foo {
import Foo._
println(x)
}