I am trying to create a type class inside IntelliJ Scala Worksheet. So I started with trait like this
trait Show[A] {
def show(a : A) : String
}
Implicit resolution tries companion objects so your code seems ok. However for an object to become a companion it must satisfy the following two requirements
The following warning means the second requirement is not satisfied:
defined object Show
warning: previously defined trait Show is not a companion to object Show.
Companions must be defined together; you may wish to use :paste mode for this.
To satisfy second requirement we have to use Plain
evaluation model in Scala Worksheet, or :paste
mode in Scala REPL.
To define a companion object in IntelliJ Scala Worksheet change Run type
to Plain
like so
Settings for *.sc
Run type
from REPL
to Plain
As per @jwvh suggestion, make sure to enter paste mode
If a class or object has a companion, both must be defined in the same file. To define companions in the REPL, either define them on the same line or enter :paste mode.
as demonstrated here.
Your example appears to work as expected when run as a scala script.
With the following in a file named test.sh
and marked executable
#!/usr/bin/env scala
trait Show[A] {
def show(a : A) : String
}
object Show {
def show[A](a: A)(implicit sh: Show[A]) = sh.show(a)
implicit val intCanShow: Show[Int] =
new Show[Int] {
def show(int: Int): String = s"int $int"
}
}
println(Show.show(20))
I observe
bash-3.2$ ./test.sh
int 20