Is it possible to define companion classes/modules in the Scala interpreter? - scala

It's often convenient to test things out in the Scala interpreter. However, one issue I run into is that I have to restructure code that uses implicit conversions because defining an object with the same name as an existing class does not make it a companion module in the REPL. As a result, I can't be confident my code will still work when I translate back to "real source".
Is there a way to define companions in the REPL? Maybe something along the lines of
bigblock {
class A
object A {
implicit def strToA(s: String): A = // ...
}
}
such that
val v: A = "apple"
will compile.

That's close:
object ABlock {
class A
object A {
implicit def strToA(s: String): A = // ...
}
}
import ABlock._
Or, the following, if you put everything on one line:
class A; object A { implicit def strToA(s: String): A = // ... } }
...though either way you'll still need to import the implicit conversion to make the following work as you requested:
import ABlock.A.strToA // for the form with the enclosing object
import A.strToA // for the one-line form without an enclosing object
val v: A = "apple"
The reason you need to do this is that every line you enter at the REPL is enclosed in an object and each subsequent one is nested within the immediately preceding one. This is done so you can do things like the following without getting redefinition errors:
val a = 5
val a = "five"
(Effectively, the second definition of a here shadows the first.)

With more recent versions use can use the :paste command.

Related

Option and null in Scala

If I have the following function:
def getOrNull[T >: Null](f: => T): T = {
try { f } catch { case _: NullPointerException => null }
}
And I want to use it with Option like so:
val r = Option(getOrNull(someString.split("/")(0)))
I get:
Error:(25, 19) Option.type does not take parameters
What is going on, and how can I overcome this?
You might wonder what Option you are referring to.
From sbt console, use //print<tab>:
scala> Option //print
scala.Option // : Option.type
For better context:
package nooption
class Option(arg: String) // some other option on class path
object Option
object Test {
import scala.reflect.internal.util.ScalaClassLoader
def main(args: Array[String]): Unit = println {
//Option(null)
//ScalaClassLoader.originOfClass(classOf[Option])
ScalaClassLoader.originOfClass(classOf[Option$])
}
}
The class name for the companion object has a dollar at the end.
Your IDE might "go to definition."
If you started a REPL at the command line, class files in the current directory are on its class path. If you previously compiled an Option in the default or "empty" package, it will hide scala.Option.
As noted in the comments, this code does compile OK, but you really shouldn't use null in Scala unless you are interfacing with Java.
This is a better way of implementing your code:
val r = Try{ someString.split("/")(0) }.toOption
Try is widely used in Scala so this code is clear to anyone experienced with the language, so there is no need for a separate function.

Scala: Use implicits in companion object

I am creating companion object in scala and trying to use object implictis functions in class without import. But whenever, trying to compile the code I am getting an error: type mismatch; seems it is not able to import implictis automatically. Following is my code:
object ImplicitTest5 {
implicit def dollarToRupa(dollar: Dollar): Rupa = {
println("calling .... dollarToEuro")
Rupa(dollar.value)
}
implicit def dollarToEuro(dollar: Dollar): Euro = {
println("calling .... dollarToEuro")
Euro(dollar.value)
}
}
case class Dollar(value: Double)
case class Euro(value: Double)
case class Rupa(value: Double)
class ImplicitTest5 {
private val value = "String"
def conversion = {
val euro: Euro = Dollar(3.1)
println(s" ----- $euro")
}
}
When i am using import ImplicitTest5._ in my class, it will compile and run fine. According to Programming in Scala, Page: 478 it will be working fine, and there is no need to define import.
In this case, the conversion dollarToEuro is said to be associated to
the type Dollar. The compiler will find such an associated conversion
every time it needs to convert from an instance of type Dollar.
There’s no need to import the conversion separately into your program.
Something is going wrong with my sample or my understandings are misleading ?
Something is going wrong with my sample or my understandings are
misleading
The conversion to Dollar will be associated with it if you define it inside Dollars companion object. Currently, all your implicits are defined on ImplicitTest5, which isn't where the compiler looks for implicits in regards to the Dollar class. This forces you to explictly import the object containing those implicits. Instead, do:
case class Dollar(value: Double)
object Dollar {
implicit def dollarToEuro(dollar: Dollar): Euro = {
println("calling .... dollarToEuro")
Euro(dollar.value)
}
}
For more, see "Where does Scala look for implicits"
By default scala compiler will look into the companion object of source and target objects. So if for example you are converting from Dollor to Euro, the implicit method can be in Dollor or Euro companion object. The compiler will pick it automatically. Otherwise you have to bring it explicitly in the scope.

Robustness of pattern matching Trees with quasiquotes

I have a macro and part of that macro consists of replacing every call to a certain method with something else. To accomplish this I use a Transformer and try to match every Tree that enters the transform method against a quasiquote. When I write it like below, it seems to work.
package mypackage
object myobject {
implicit def mymethod[T](t: Option[T]): T = ???
}
object Macros {
import scala.language.experimental.macros
import scala.reflect.macros.blackbox.Context
def myMacro(c: Context)(expr: c.Tree): c.Tree = {
import c.universe._
val transformer = new Transformer {
private def doSomething(value: c.Tree): TermName = {
???
}
override def transform(tree: c.Tree) = tree match {
case q"mypackage.myobject.mymethod[..$_]($value)" =>
val result = doSomething(value)
q"$result"
case _ => super.transform(tree)
}
}
val transformed = transformer.transform(expr)
???
}
}
But I thought you should always use fully qualified names in macros or you could get into trouble. So I wrote it like q"_root_.mypackage.myobject.mymethod[..$_]($value)", but then it no longer matched and the calls to mymethod no longer got replaced.
I also looked at the suggestion in the scala docs to unquote symbols, but I couldn't get that to work either.
So my question is: will this code (with q"mypackage.myobject.mymethod[..$_]($value)") always replace all the calls to mymethod and never replace any other method calls? And if not, how can I make it more robust?
scala.reflect macros are non hygienic, so, theoretically, q"mypackage.myobject.mymethod[..$_]($value)" could be matched by someone else.
I'd suggest match that method with q"..$mods def $name[..$tparams](...$paramss): $tpeopt = $expr" (assuming that is definition, not declaration). You can add checks on name.
Another solution is to mark method with annotation, and remove it in macro phase.

Scala implicit parameter scope

I've spent all morning reading up on how Scala scopes implicits, including the very excellent answer here: Where does Scala look for implicits?
But alas, I am still confused. Let me give an example of what I'm trying to do:
object Widget {
implicit val xyz: Widget = new Widget("xyz")
}
class Widget(val name: String) {
override def toString = name
}
class Example {
def foo(s: String)(implicit w: Widget): Unit = {
println(s"Got $s with $w")
}
def bar {
foo("abc") // Compiler error at this line
}
}
object implicit_test {
val x = new Example()
x.bar
}
So, I expect to see something like Got abc with xyz. Instead I get told could not find implicit value for parameter w: Widget. Now, strangely if I move the Widget class and object as well as the Example class inside the implicit_test object, then this works.
Please explain to me again, if you will, how exactly Scala identifies which implicit val to use!
Your code should work and it does work for me.
Did you by chance type that in the REPL? If so, there is something special concerning companion objects. In scala, a companion object must be in the same file as its class (otherwise, the code is valid, but it is not a "companion object", just an object with the same name, and not part of the implicit scope). In the REPL, there are no files, but the class and its companion object must be defined at the same time. To do that, you must enter them in paste mode.
Type :paste, then paste (or just type) at least both the object Widget and the class Widget (you may paste the rest to the code at the same time, but it is not necessary), and then CTRL-D. That should work.

How can I add new methods to a library object?

I've got a class from a library (specifically, com.twitter.finagle.mdns.MDNSResolver). I'd like to extend the class (I want it to return a Future[Set], rather than a Try[Group]).
I know, of course, that I could sub-class it and add my method there. However, I'm trying to learn Scala as I go, and this seems like an opportunity to try something new.
The reason I think this might be possible is the behavior of JavaConverters. The following code:
class Test {
var lst:Buffer[Nothing] = (new java.util.ArrayList()).asScala
}
does not compile, because there is no asScala method on Java's ArrayList. But if I import some new definitions:
class Test {
import collection.JavaConverters._
var lst:Buffer[Nothing] = (new java.util.ArrayList()).asScala
}
then suddenly there is an asScala method. So that looks like the ArrayList class is being extended transparently.
Am I understanding the behavior of JavaConverters correctly? Can I (and should I) duplicate that methodology?
Scala supports something called implicit conversions. Look at the following:
val x: Int = 1
val y: String = x
The second assignment does not work, because String is expected, but Int is found. However, if you add the following into scope (just into scope, can come from anywhere), it works:
implicit def int2String(x: Int): String = "asdf"
Note that the name of the method does not matter.
So what usually is done, is called the pimp-my-library-pattern:
class BetterFoo(x: Foo) {
def coolMethod() = { ... }
}
implicit def foo2Better(x: Foo) = new BetterFoo(x)
That allows you to call coolMethod on Foo. This is used so often, that since Scala 2.10, you can write:
implicit class BetterFoo(x: Foo) {
def coolMethod() = { ... }
}
which does the same thing but is obviously shorter and nicer.
So you can do:
implicit class MyMDNSResolver(x: com.twitter.finagle.mdns.MDNSResolver) = {
def awesomeMethod = { ... }
}
And you'll be able to call awesomeMethod on any MDNSResolver, if MyMDNSResolver is in scope.
This is achieved using implicit conversions; this feature allows you to automatically convert one type to another when a method that's not recognised is called.
The pattern you're describing in particular is referred to as "enrich my library", after an article Martin Odersky wrote in 2006. It's still an okay introduction to what you want to do: http://www.artima.com/weblogs/viewpost.jsp?thread=179766
The way to do this is with an implicit conversion. These can be used to define views, and their use to enrich an existing library is called "pimp my library".
I'm not sure if you need to write a conversion from Try[Group] to Future[Set], or you can write one from Try to Future and another from Group to Set, and have them compose.