There is actually more than the type names between val
and object
.
You know, object
in Scala is something like a singleton in Java.
Maybe you thought that both string
and BooleanShow
are in an object
not a class
so they have no difference, but that's not true.
They are val
and object
no matter what.
Try this in Scala REPL.
trait Show[T] {
def show(obj: T): String
}
object Show {
println("!! Show created")
implicit val string = new Show[String] {
println("!! string created")
def show(obj: String): String = obj
}
implicit object BooleanShow extends Show[Boolean] {
println("!!BooleanShow created")
def show(obj: Boolean): String = obj.toString
}
}
If only the definition is done, then no println
s are executed afterwards, since Show
is a singleton in effect. It's not created yet.
Next, execute Show
in Scala REPL.
scala> Show
res0: Show.type = Show$@35afff3b
You see, println
s in Show
and Show.string
were called, but the one in Show.BooleanShow
was not.
You can execute Show.BooleanShow
next in Scala REPL.
scala> Show.BooleanShow
!!BooleanShow created
res1: Show.BooleanShow.type = Show$BooleanShow$@18e419c5
Show.BooleanShow
was initialized at last. It is a singleton, so it is lazy.
Basically, your question is the same as val and object inside a scala class? except that your val
and object
are defined in an object
, but the linked question tries to find differences val
and object
defined in a class
and the method in val
uses reflection (but yours uses overriding, so no reflection is involved). implicit
basically does not make difference in what they are.
I think you already know the difference between class
and object
. Further information can be found in the linked question.
object
the name will be clearer. – cchantepimplicit val
instead ofval implicit
. – bmaderbacherval
anonymous class is used, with readability issue in stack trace, I don't see anything more. – cchantep