Last active
September 30, 2015 13:38
-
-
Save speedcom/1a0f358532207985ae6a to your computer and use it in GitHub Desktop.
implicit conversion from one type to another one
This file contains 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
// implicit conversion from one type to another one | |
// 1 way | |
object ViewBound { | |
trait Show { | |
def show: String | |
} | |
object Show { | |
implicit class ShowDouble(x: Double) extends Show { | |
def show: String = f"$x%.2f" | |
} | |
implicit class ShowSymbol(x: Symbol) extends Show { | |
def show: String = ":" + x.name | |
} | |
} | |
object Main { | |
def pokaz_1[T](v: T)(implicit f: T => Show) = print(v.show) | |
def pokaz_2[T <% Show](v: T) = print(v.show) | |
} | |
} | |
// 2 way | |
object ContextBound { | |
trait Show[T] { | |
def show(x: T): String | |
} | |
object Show { | |
implicit object ShowDouble extends Show[Double] { | |
def show(x: Double): String = f"$x%.2f" | |
} | |
implicit object ShowSymbol extends Show[Symbol] { | |
def show(x: Symbol): String = ":" + x.name | |
} | |
} | |
def toShow[T](f: T => String): Show[T] = new Show[T] { | |
override def show(t: T): String = f(t) | |
} | |
def apply[T](implicit showT: Show[T]): Show[T] = showT | |
implicit val LongShow = toShow[Long](_.toString) | |
implicit val DoubleShow = toShow[Double](_.toString) | |
object Main extends Any { | |
def pokaz_1[T](v: T)(implicit f: Show[T]) { | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment