n this introduction to Scala, I will demonstrate why I love Scala and why I think that you will too. You’ll learn why you don’t need to go from 0 to functions and how you can ease yourself into this language. I’ll show you some Scala, compare it to Java, and give you pointers on how to start your journey into this functional object-oriented language.
2. Dr. Strangelove, 1964
“If this thing turns out
to be half as important
as I think it will be, I
think you’ll all be in
line for some personal
citations and
promotions when this
thing is over.”
9. Anatomy of a Case Class
case class Camera(width: Int,
height: Int) {
def megapixels = (width * height)
/1000000.0
def HD = megapixels > 1.08
}
val camera = new Camera(1024, 768)
camera.megapixels is 0.786432
camera.HD is false
camera is "Camera(1024,768)"
10. Reducing Boilerplate
class Dimension(var height:Int,
var width:Int)
val c = new Dimension(5,7)
c.height is 5
c.height = 10
c.height is 10
c.width = 19
c.width is 19
15. Reaching into Java
import org.apache.commons.math._
import stat.regression.SimpleRegression
val r = new SimpleRegression
r.addData(1, 1)
r.addData(2, 1.1)
r.addData(3, 0.9)
r.addData(4, 1.2)
r.getN is 4
r.predict(6) is 1.19
17. Verbose Version
// Euler1.scala
val nums = 3 until 1000
val somenums = nums.filter
(x => (x % 3 == 0 || x % 5 ==0))
var sum = 0
somenums.foreach(sum += _)
18. Find the Sweet Spot
// Euler2.scala
val nums = 3 until 1000
val somenums = nums filter
(x => (x % 3 == 0 || x % 5 ==0))
val sum = somenums reduceLeft
{(x:Int,y:Int) => x + y}
19. More than 1 way ...
// Euler3.scala
val nums = 3 until 1000
val somenums = nums filter
(x => (x % 3 == 0 || x % 5 ==0))
val sum = somenums.foldLeft(0)(_+_)
20. Back off if it’s too much
// Euler4.scala
val nums = 3 until 1000
val somenums = nums filter
(x => (x % 3 == 0 || x % 5 ==0))
(0/:somenums)(_+_)
21. Code should be readable
To your team
To your customers
To yourself, in 6 months