Skip to content

Instantly share code, notes, and snippets.

@ioleo
Forked from kubukoz/OneWayImplicits.scala
Last active July 16, 2017 21:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ioleo/1c5156494b6f1b9fb9d84ff907b0f4c8 to your computer and use it in GitHub Desktop.
Save ioleo/1c5156494b6f1b9fb9d84ff907b0f4c8 to your computer and use it in GitHub Desktop.
object OneWayImplicits extends App {
//outside implicits visible, but T is not visible inside
case class Outwards[T](value: T) extends AnyVal
//outside implicits invisible, T is visible inside
case class Inwards[T](value: T) extends AnyVal
implicit def outwardsFromT[T](implicit t: T): Outwards[T] = Outwards(t)
implicit def tFromInwards[T](implicit inw: Inwards[T]): T = inw.value
type X = String
def printX(implicit x: X) = println(x)
def usesOutwards()(implicit ow: Outwards[X]) = {
//X is not implicitly visible here
val x: X = ow.value
println("usesOutwards")
printX(x)
}
def testOutwards() = {
implicit val x: X = "iks out"
usesOutwards()
}
testOutwards()
def usesInwards()(implicit iw: Inwards[X]) = {
println("usesInwards")
//doesn't get X from implicit scope
//but X is implicitly visible here
printX
}
def testInwards() = {
implicit val iw: Inwards[X] = Inwards("iks in")
usesInwards()
}
testInwards()
def composability()(implicit x: Inwards[X]) = {
println("composability")
usesOutwards() //gets `Outwards(x.value)`
}
def testComposability() = {
implicit val iw: Inwards[X] = Inwards("iks compose")
composability()
}
testComposability()
// prints:
// ==============
// usesOutwards
// iks out
// usesInwards
// iks in
// composability
// usesOutwards
// iks compose
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment