name; private String work; public void setName(String name) { this.name = name; } public String getName() { return name; } public void setWork(String work) { this.work = work; } public String getWork() { return work; } } Person.java Job.java public class Job { public void main(String[] args) { Person kevin = new Person(); kevin.setName("Kevin"); kevin.setWork("Between"); } } job.scala class Person(val name: String, val work: String) val kevin = new Person("Kevin", "Between") ݽۄ.. GOOD
(X) • Scalaח Pure OOP class Person(val name: String, val work: String) val kevin = new Person("Kevin", "Between") • Scalaח Functional Programming оמ val list = List(1, 2, 3) def aMultiplyFunction(x: Int) = { x * 2 } val result = list.map(aMultiplyFunction) ೣࣻо 1st-class citizen! ೣࣻܳ ؘఠ۽ рೞҊ, ੋ۽ ֈӝח ١ ೯ਤо оמ
"A".equals("B") // Scala "A" == "B" case class Person(name: String, work: String) val kevin = Person("Kevin", "Between") val anotherKevin = Person("Kevin", “Between”) kevin == anotherKevin // true case class ࢤࢿীח new о ਃ হ • ܻੋ class equality
val input2 = Chart("2014-12-02", 50) val input3 = ("spark-techtalk", 100) def matchTest(x: Any): Any = { x match { case 1 => "one" case "two" => 2 case (key, value) => s"key: $key, value: $value" case Chart(date, count) => s"date: $date, count: $count" case _ => "others" } } matchTest(input1) res0: Any = others matchTest(input2) res1: Any = date: 2014-12-02, count: 50 matchTest(input3) res2: Any = key: spark-techtalk, value: 100 Pattern Matching & Case Class • Java switch ~ case ৬ ࠺तೞ݅, ഻ঁ ъ۱ೠ بҳ ܲ ઙܨ ఋੑۄب ݒ оמ case case class ഝਊೞݶ ؊ ಞܻ case class: ؘఠ ҳઑചী ಞܻ
logFile = new java.io.File(path + "example_log.txt") val log = scala.io.Source.fromFile(logFile).getLines().toList // parse log and get sign up numbers case class LogEntry(dateTime: String, action: String, id: String) val logEntries = log.map(csv => csv.split(",")).map(arr => LogEntry(arr(0), arr(1), arr(2))).toList // get sign up val logEntriesToday = logEntries.filter(_.dateTime.contains("2014-12-04")) val signUp = logEntriesToday.filter(_.action == "SIGN_UP").size // active user val userIds = logEntriesToday.map(_ id) val activeUser = userIds.distinct.size
sc.textFile("file:///example_log.txt") // parse log and get sign up numbers case class LogEntry(dateTime: String, action: String, id: String) val logEntries = log.map(csv => csv.split(",")).map(arr => LogEntry(arr(0), arr(1), arr(2))) // get sign up val logEntriesToday = logEntries.filter(_.dateTime.contains("2014-12-04")) val signUp = logEntriesToday.filter(_.action == "SIGN_UP").count // active user val userIds = logEntriesToday.map(_ id) val activeUser = userIds.distinct.count Scala collection API৬ Ѣ ৮ زੌ!