-
-
Save ioleo/1c5156494b6f1b9fb9d84ff907b0f4c8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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