Skip to content

Instantly share code, notes, and snippets.

implicit val bob = "Bob"
def greet(implicit name: String) = {
println(s"Hello, $name!")
}
// usage
greet
// outputs "Hello, Bob!"
implicit val bob = "Bob"
implicit val alice = "Alice"
def greet(implicit name: String) = {
println(s"Hello, $name!")
}
// usage
greet
implicit def intToStr(num: Int): String = s"The value is $num"
42.toUpperCase() // evaluates to "THE VALUE IS 42"
def functionTakingString(str: String) = str
// note that we're passing int
functionTakingString(42) // evaluates to "The value is 42"
object Helpers {
implicit class StringOps(str: String) {
def yell = str.toUpperCase() + "!"
def isQuestion = str.endsWith("?")
}
}
"Hello world".yell // evaluates to "HELLO WORLD!"
"How are you?".isQuestion // evaluates to 'true'
case class StringOps(str: String) {
def yell = str.toUpperCase() + "!"
def isQuestion = str.endsWith("?")
}
case class StringOps(str: String) {
def yell = str.toUpperCase() + "!"
def isQuestion = str.endsWith("?")
}
implicit def stringToStringOps(str: String): StringOps = StringOps(str)
"Hello world".yell // evaluates to "HELLO WORLD!"
"How are you?".isQuestion // evaluates to 'true'
// Our interface
trait Monoid[A] {
def zero: A
def plus(a: A, b: A): A
}
// Implementation for integers
implicit object IntegerMonoid extends Monoid[Int] {
override def zero: Int = 0
override def plus(a: Int, b: Int): Int = a + b
def sum[A](values: Seq[A])(implicit ev: Monoid[A]): A
def sum[A:Monoid](values: Seq[A]): A
def sum[A:Monoid](values: Seq[A]): A = {
val ev = implicitly[Monoid[A]]
values.foldLeft(ev.zero)(ev.plus)
}
def implicitly[T](implicit e: T) = e