Upcoming SlideShare
×

# Scala implicits

1,467 views

Published on

Introduction to

3 Likes
Statistics
Notes
• Full Name
Comment goes here.

Are you sure you want to Yes No
• Be the first to comment

Views
Total views
1,467
On SlideShare
0
From Embeds
0
Number of Embeds
9
Actions
Shares
0
0
0
Likes
3
Embeds 0
No embeds

No notes for slide

• ### Scala implicits

1. 1. Implicits 2 Features, 1 Keyword Nick Partridge @nkpart
2. 2. 2 Features • Implicit Conversions • Implicit Parameters
3. 3. Conversions • int a = 5.3f; // Implicit conversion
4. 4. Conversions • val a: A = ...; • val b: B = a; // Compile Fail. Of course.
5. 5. Conversions • val a: A = ...; • implicit def (a: A): B = ...; • val b: B = a; • // Proﬁt.
6. 6. Conversions Compiler searches the ‘implicit scope’ • val b: B = a; • val b: B = bToA(a);
7. 7. Pimp My Library Live Demo.
8. 8. Conversions • Also triggered by a method search case class Foo(s: String) { def pl = s + “es” }
9. 9. Conversions implicit def toFoo(s: String) = Foo(s) “peach”.pl // == “peaches” toFoo(s).pl
10. 10. Not Transitive Implicit A => B Implicit B => C Does not mean Implicit A => C
11. 11. View Bounds Live coding!
12. 12. The End. Of Part 1.
13. 13. Parameters
14. 14. Parameters • Scala functions have parameter groups • def foo(a: Int)(b: Int)(c: Int) = ... • foo(1)(2)(3)
15. 15. Parameters • The *last* group can be `implicit`. • def mungeData(d: Data)(implicit m: Munger) • mungeData(myData)(myMunger)
16. 16. Parameters • implicit val myMunger = new Munger • mungeData(myData)(myMunger) Compiler ﬁgures out the last group
17. 17. Parameters • def mungeData[D](d: D)(implicit m: Munger[D]) • mungeData(“foo”) // Compiler ﬁnds a Munger[String]
18. 18. Parameters • Higher kinds! • def mungeData[M[_], D](d: D)(implicit m: Munger[D], each: Each[M]) = ... • mungeData(List(1,2,3)) • Munger[Int] • Each[List]
19. 19. Live demo! Monoid!
20. 20. Conversions Parameters
21. 21. Where to get the ‘implicits’ from?
22. 22. Implicit Search Scope • Similar to value resolution scope • local variables, values in current object, super classes. • Imported object members • Function parameters
23. 23. Implicit Search Scope // COMPANION OBJECTS trait Monoid[T] object Monoid { // SAME NAME implicit val s = new Monoid[String] } // `s` will be available anywhere a Monoid[String] is needed. Without imports.
24. 24. Implicit Search Scope def foo[T](t: T)(implicit m: Monoid[T]) = { // m is available for any implicit parameters needed within this method body }
25. 25. More! • Anonymous functions • implicit r => { ... } • Import instances • case class Z(a: A) { implicit ia = a } • val z = new Z(someA) • import z._
26. 26. Wonderful and Terrible.
27. 27. La ﬁn.