Skip to content

Instantly share code, notes, and snippets.

@Allan-Gong
Last active December 10, 2015 05:42
Show Gist options
  • Save Allan-Gong/e22c8a4fd1edac15bd64 to your computer and use it in GitHub Desktop.
Save Allan-Gong/e22c8a4fd1edac15bd64 to your computer and use it in GitHub Desktop.
Demonstrate implicit in Scala
/*******************************/
/***** Implicit conversion *****/
/*******************************/
// If one calls a method m on an object o of a class C, and that class does not support method m,
// then Scala will look for an implicit conversion from C to something that does support m.
// Use to automatically convert a value from one type to another
val value:BigInt = 1
// What actually happened is:
val value:BigInt = math.BigInt.int2bigInt(1)
// This is done by the scala compiler, it finds an implicit function that can convert Int to BigInt in its current scope:
implicit def int2bigInt(i: Int): BigInt = apply(i)
/*******************************/
/***** Implicit parameters *****/
/*******************************/
// The final parameter list on a method can be marked implicit, which means the values will be taken from the context in which they are called.
// If there is no implicit value of the right type in scope, it will not compile.
// Since the implicit value must resolve to a single value and to avoid clashes, it's a good idea to make the type specific to its purpose
class Prefixer(val prefix: String)
def addPrefix(s: String)(implicit p: Prefixer) = p.prefix + s
implicit val myImplicitPrefixer = new Prefixer("***")
addPrefix("abc") // returns "***abc"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment