Skip to content

Instantly share code, notes, and snippets.

@gigiigig
Created March 3, 2015 10:45
Show Gist options
  • Save gigiigig/a6303d2ccb649a5e4d3e to your computer and use it in GitHub Desktop.
Save gigiigig/a6303d2ccb649a5e4d3e to your computer and use it in GitHub Desktop.
Implicits Abiguous and Override
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent._
import scala.concurrent.duration._
import scalaz._
import Scalaz._
object console extends App {
object ambiguous {
object Foo {
implicit val s: String = "foo"
}
object Bar {
implicit val st: String = "bar"
}
def printS(implicit string: String) = println(s"s: ${string}")
import Foo._
import Bar._
// printS
// [error] /home/luigi/workspace/test-scalaz-shapeless/src/main/scala/console.scala:26: ambiguous implicit values:
// [error] both value s in object Foo of type => String
// [error] and value st in object Bar of type => String
// [error] match expected type String
}
object implicitOverrride {
// this work because Bar extends Foo
trait Foo {
implicit val s: String = "foo"
}
object Bar extends Foo {
implicit val st: String = "bar"
}
val foo: Foo = new Foo {}
def printS(implicit string: String) = println(s"s: ${string}")
import foo._
import Bar._
printS // s: bar
}
implicitOverrride
object hiddenByName {
object Foo {
implicit val s: String = "foo"
}
object Bar {
val s: Int = 2
}
def printS(implicit string: String) = println(s"s: ${string}")
import Foo._
import Bar._
// printS
// [error] /home/luigi/workspace/test-scalaz-shapeless/src/main/scala/console.scala:72:
// could not find implicit value for parameter string: String
}
// This is important!!
object hiddenByName2 {
object Foo {
implicit val s: String = "foo"
}
object Bar {
implicit val st: String = "bar"
}
def printS(implicit string: String) = println(s"s: ${string}")
import Foo._
import Bar._
implicit val s: String = "ciao"
printS
// WILL PRINT "bar"
}
hiddenByName2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment