diff --git a/tutorials/tour/_posts/2017-02-13-implicit-conversions.md b/tutorials/tour/_posts/2017-02-13-implicit-conversions.md deleted file mode 100644 index 82bed34611..0000000000 --- a/tutorials/tour/_posts/2017-02-13-implicit-conversions.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -layout: tutorial -title: Implicit Conversions - -disqus: true - -tutorial: scala-tour -categories: tour -num: 27 -next-page: polymorphic-methods -previous-page: implicit-parameters ---- - -An implicit conversion from type `S` to type `T` is defined by an implicit value which has function type `S => T`, or by an implicit method convertible to a value of that type. - -Implicit conversions are applied in two situations: - -* If an expression `e` is of type `S`, and `S` does not conform to the expression's expected type `T`. -* In a selection `e.m` with `e` of type `S`, if the selector `m` does not denote a member of `S`. - -In the first case, a conversion `c` is searched for which is applicable to `e` and whose result type conforms to `T`. -In the second case, a conversion `c` is searched for which is applicable to `e` and whose result contains a member named `m`. - -The following operation on the two lists xs and ys of type `List[Int]` is legal: - -``` -xs <= ys -``` - -assuming the implicit methods `list2ordered` and `int2ordered` defined below are in scope: - -``` -implicit def list2ordered[A](x: List[A]) - (implicit elem2ordered: A => Ordered[A]): Ordered[List[A]] = - new Ordered[List[A]] { /* .. */ } - -implicit def int2ordered(x: Int): Ordered[Int] = - new Ordered[Int] { /* .. */ } -``` - -The implicitly imported object `scala.Predef` declares several predefined types (e.g. `Pair`) and methods (e.g. `assert`) but also several implicit conversions. - -For example, when calling a Java method that expects a `java.lang.Integer`, you are free to pass it a `scala.Int` instead. That's because Predef includes the following implicit conversions: - -```tut -import scala.language.implicitConversions - -implicit def int2Integer(x: Int) = - java.lang.Integer.valueOf(x) -``` - -Because implicit conversions can have pitfalls if used indiscriminately the compiler warns when compiling the implicit conversion definition. - -To turn off the warnings take either of these actions: - -* Import `scala.language.implicitConversions` into the scope of the implicit conversion definition -* Invoke the compiler with `-language:implicitConversions` - -No warning is emitted when the conversion is applied by the compiler. diff --git a/tutorials/tour/_posts/2017-02-13-implicit-parameters.md b/tutorials/tour/_posts/2017-02-13-implicit-parameters.md deleted file mode 100644 index 40e72ab3ac..0000000000 --- a/tutorials/tour/_posts/2017-02-13-implicit-parameters.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -layout: tutorial -title: Implicit Parameters - -disqus: true - -tutorial: scala-tour -categories: tour -num: 26 -next-page: implicit-conversions -previous-page: explicitly-typed-self-references ---- - -A method with _implicit parameters_ can be applied to arguments just like a normal method. In this case the implicit label has no effect. However, if such a method misses arguments for its implicit parameters, such arguments will be automatically provided. - -The actual arguments that are eligible to be passed to an implicit parameter fall into two categories: - -* First, eligible are all identifiers x that can be accessed at the point of the method call without a prefix and that denote an implicit definition or an implicit parameter. -* Second, eligible are also all members of companion modules of the implicit parameter's type that are labeled implicit. - -In the following example we define a method `sum` which computes the sum of a list of elements using the monoid's `add` and `unit` operations. Please note that implicit values can not be top-level, they have to be members of a template. - -```tut -/** This example uses a structure from abstract algebra to show how implicit parameters work. A semigroup is an algebraic structure on a set A with an (associative) operation, called add here, that combines a pair of A's and returns another A. */ -abstract class SemiGroup[A] { - def add(x: A, y: A): A -} -/** A monoid is a semigroup with a distinguished element of A, called unit, that when combined with any other element of A returns that other element again. */ -abstract class Monoid[A] extends SemiGroup[A] { - def unit: A -} -object ImplicitTest extends App { - /** To show how implicit parameters work, we first define monoids for strings and integers. The implicit keyword indicates that the corresponding object can be used implicitly, within this scope, as a parameter of a function marked implicit. */ - implicit object StringMonoid extends Monoid[String] { - def add(x: String, y: String): String = x concat y - def unit: String = "" - } - implicit object IntMonoid extends Monoid[Int] { - def add(x: Int, y: Int): Int = x + y - def unit: Int = 0 - } - /** This method takes a List[A] returns an A which represent the combined value of applying the monoid operation successively across the whole list. Making the parameter m implicit here means we only have to provide the xs parameter at the call site, since if we have a List[A] we know what type A actually is and therefore what type Monoid[A] is needed. We can then implicitly find whichever val or object in the current scope also has that type and use that without needing to specify it explicitly. */ - def sum[A](xs: List[A])(implicit m: Monoid[A]): A = - if (xs.isEmpty) m.unit - else m.add(xs.head, sum(xs.tail)) - - /** Here we call sum twice, with only one parameter each time. Since the second parameter of sum, m, is implicit its value is looked up in the current scope, based on the type of monoid required in each case, meaning both expressions can be fully evaluated. */ - println(sum(List(1, 2, 3))) // uses IntMonoid implicitly - println(sum(List("a", "b", "c"))) // uses StringMonoid implicitly -} -``` - -Here is the output of the Scala program: - -``` -6 -abc -``` diff --git a/tutorials/tour/_posts/2017-02-13-implicits.md b/tutorials/tour/_posts/2017-02-13-implicits.md new file mode 100644 index 0000000000..87e3ef602d --- /dev/null +++ b/tutorials/tour/_posts/2017-02-13-implicits.md @@ -0,0 +1,84 @@ +--- +layout: tutorial +title: Implicits + +disqus: true + +tutorial: scala-tour +categories: tour +num: 26 +next-page: implicit-conversions +previous-page: explicitly-typed-self-references +--- +Implicits allow for automatic application of code when an explicit application isn't supplied. + +## Implicit parameters + +Implicit parameters allow for the caller to omit an argument if an implicit one is in scope. Use the `implicit` keyword to make a value, object, or expression implicit. You also use it to make the parameter list implicit. +```tut +class Greeting(val greeting: String) { + def greet(name: String) = s"$greeting, $name" +} +implicit val standardGreeting = new Greeting("Hello") + + +def printGreeting(name: String)(implicit greeting: Greeting) = greeting.greet(name) + + +printGreeting("Franchesca") // Hello, Franchesca +printGreeting("Fred")(new Greeting("Good day")) // Good day, Fred +``` +The `implicit val standardGreeting` is a value that can be supplied as an argument to an implicit parameter automatically. In the method `printGreeting`, the parameter `greeting` is implicit. This means that the caller can either supply an argument normally or skip it. With `greet("Franchesca")`, the compiler doesn't see a greeting but it notices that `greeting` is an implicit parameter so it searches the current scope for an implicit `Greeting` and finds `standardGreeting`. + +This becomes useful when you have a lot of similar arguments to function calls throughout your program. However, implicits can make code more difficult to understand because it's not always obvious where they're defined if you import them from another module with a wildcard (e.g. `import MyPredef._`). + + + + +## Implicit conversion + + +An implicit conversion happens the type check fails for an argument and an implicit conversion is found. +``` +def square(x: Double) = x * x +val number: Int = 5 +square(number) // 25.0 +``` +This typecasting happens because of the method `implicit def int2double(x: Int): Double = x.toDouble` defined in `Predef` (a set of convenience methods in scope by default). When the compiler sees that `square` expects a `Double` but we pass an `Int`, it searches the scope for an `implicit` function that can do the conversion. + +Implicits conversions can be useful when you're making a lot of calls to an API and the calls are verbose or require a type conversion. For example, if you want to create a button using Java swing, the code is verbose: +```tut +import scala.language.implicitConversions +import java.awt.event.{ActionEvent, ActionListener} +import javax.swing.JButton + +val button = new JButton +button.addActionListener( + new ActionListener { + def actionPerformed(event: ActionEvent) = { + println("pressed!") + } + } +) +``` +You would need to write this same code for every button in order to _print "pressed" when the button is pressed_. You could instead abstract this away to an implicit conversion: +```tut +import java.awt.event.{ActionEvent, ActionListener} +import javax.swing.JButton + +implicit def function2ActionListener(f: ActionEvent => Unit) = + new ActionListener { + def actionPerformed(event: ActionEvent) = f(event) + } + + +val button = new JButton +button.addActionListener( + (_: ActionEvent) => println("pressed!") +) +``` +The implicit method `function2ActionListener` takes a function which accepts an ActionEvent. It then returns an `ActionListener` with the aforementioned function as its `actionPerformed`. Now when we call `button.addActionListener` (which accepts an `ActionListener`) with an anonymous function of type `ActionEvent => Unit`, the compiler looks for an implicit conversion function which can convert the type to `ActionListener`. + +This removes a lot of the boilerplate because we can use an anonymous function. However, because implicits are often defined outside of the package, it can be difficult to debug. Therefore they are best used in libraries. + +_Example Credit_: Odersky, Martin, Lex Spoon, and Bill Venners. Programming in Scala. Walnut Creek, CA: Artima, 2016.