SlideShare a Scribd company logo
1 of 40
Download to read offline
Scala 初探
亦思科技 鄭紹志
vito@is-land.com.tw
WHO AM I
• 鄭紹志
• IS-LAND Technical Manager
• HareDB
• Hadoop + HBase
• Scala + Spark
WHY SCALA
WHY NOT SCALA
• Scala - The good, the bad and the very ugly
• http://www.slideshare.net/Bozho/scala-the-good-the-bad-and-the-very-ugly
•Why Scala
• http://www.slideshare.net/al3x/why-scala-presentation
•Today Gist: http://tinyurl.com/z8xx6ab
SCALABLE LANGUAGE
• Runs on JVM
• Concise, 簡潔
• Statically typed, 靜態型別
• Object Oriented Programming, 物件導向開發
• Functional Programming, 函數式開發
Sample Code - SparkPi
SCALA INSTALL
• Scala 2.10.x - Spark 1.0 - 1.6 都使⽤ 2.10.x
• Download Scala 2.10.x
• http://www.scala-lang.org/download/all.html
• 解壓縮 & 設定路徑
• http://www.scala-lang.org/download/install.html
SCALA INTERPRETER
• scala: Read-Evaluate-Print-Loop(REPL)
[~]$ scala
Welcome to Scala version 2.11.7 (Java HotSpot(TM) 64-Bit
Server VM, Java 1.7.0_80).
Type in expressions to have them evaluated.
Type :help for more information.
scala> val name = "Vito"
name: String = Vito
scala> println( s"Hello, $name" )
Hello, Vito
scala> println( name.getClass )
class java.lang.String
scala>
SCALA INTERPRETER
• One line execute
• Run script
• Run main class
• Shell script
• Load file: :load
• Paste mode: :paste
$ scala -e 'val name="Vito"; println(s"Hello,$name")'
$ scala hello.scala
$ scala HelloWorld.scala
$ ./script.sh
Value & Variable
• 定義常數與變數
• 優先考慮使⽤ val
var price1 = 100

price1 = 200



val price2 = 100

price2 = 200 // error: reassignment to val
Type Inference
• 推斷使⽤的型別
val name = "Vito"

val n1 = 100

val n2 = 100L

val n3: Int = 100



val n4 = 20.6F

val list = Seq("a", "b", "c")



import java.util._

val list1 = new ArrayList[String]()
STRING
// 

val s1 = "Hello"

// 

val s2 = """object HelloWorld extends App {

println("Hello, World!")

}

"""

// string interpolation

val s3 = s"[$s1] source code:n$s2"



// no escape

val s4 = raw"Hello n world."

val s5 = "Hello"(1)

val s6 = "Hello".charAt(1)
TUPLE
• Tuple2 - Tuple22
val t2a = ("a", 2)

val t2b = Tuple2("a", 2)

val t2c = new Tuple2("a", 2)

val t2d = "a" -> 2

val t5 = ("a", 100, "c", 20.5, (1,2,3))



val v1 = t2a._1 == t2a._1 // true

val v2 = t5._5 == (1,2,3) // true
OBJECT ORIENTED
// 

// . ( )

"Hello World" split " "

"Hello World".split(" ")



// operator 

"a" + "b" + "c"

"a".+("b").+("c")
IMPORT CLASS
• 預設 import
• java.lang._
• scala._
• Java *, Scala _
• scala.Predef object
import java.util._

import java.util.{List, ArrayList}
import java.util.{List=>JList, HashMap=>JHashMap}
import java.util.{Date=>_, _}
IMPORT CLASS
• Import anywhere
import org.apache.spark.{SparkContext, SparkConf, Logging}
class MyClass {

import java.util._

def printDate() = {

val date = new Date()

println(date)

}

def printFilePath() = {

import java.io.File

val file = new File("data.txt")

println(file.getAbsolutePath)

}

}
OBJECT
• Scala 沒有 Java 的 static 宣告, 可⽤ object 代替
• 想⽤ Singletion pattern 就⽤ object
• Companion Objects: 同名的 class 與 object 同時
存在
object Student {

def sayHi = println("Hi~")

}

Student.sayHi
OBJECT
class Student(val name: String) {

override def toString = s"[Student]: $name"

}



object Student {

def apply(names: String*) = {

names.map { n => new Student(n) }

}

def count(ss: Seq[Student]) = ss.size

}



val ss = Student("Vito", "John")

Student.count(ss)
RETURN VALUE
• method 傳回值不須加 return
• Every statement(expression) yields a value
val a = 5

val b = if (a>2) 0 else 1

val data = Seq(1,2,3,4,5)

val data1 = for (

num <- data

if num % 2 == 0

) yield {

num + 10

} // data1: List(12, 14)
RETURN VALUE
• Every statement(expression) yields a value
def calc(a: Int, b: Int) = try {

a / b

} catch {

case _: Throwable => 0

}



val a = calc(100, 0)
calc: (a: Int, b: Int)Int
a: Int = 0
Anonymous Functions
val data = Seq.range(1, 5)

val data2 = data.map( (s: Int) => s*2 )

val data3 = data.map( (s) => s*2 )

val data4 = data.map( _*2 )
data: Seq[Int] = List(1, 2, 3, 4)
data2: Seq[Int] = List(2, 4, 6, 8)
data3: Seq[Int] = List(2, 4, 6, 8)
data4: Seq[Int] = List(2, 4, 6, 8)
Anonymous Functions
val data = Seq.range(1, 5)

val multi = (s: Int) => s * 2

val multi2 = new Function1[Int, Int]() {

override def apply(v1: Int): Int = v1 * 2

}

val data2 = data.map(multi)

val data3 = data map multi

val data4 = data map multi2
multi: Int => Int = <function1>
multi2: Int => Int = <function1>
data2: Seq[Int] = List(2, 4, 6, 8)
data3: Seq[Int] = List(2, 4, 6, 8)
data4: Seq[Int] = List(2, 4, 6, 8)
Function ? Method ?
• ⽬前不必追究
• (想追究的😆)可從這裡先開始, 再 Google
• http://stackoverflow.com/q/2529184
map
map
val data = Seq.range(1, 5)

val multi = (s: Int) => s * 2

val data2 = data.map( _*2 )

val data3 = data map multi

data: Seq[Int] = List(1, 2, 3, 4)
multi: Int => Int = <function1>
data2: Seq[Int] = List(2, 4, 6, 8)
data3: Seq[Int] = List(2, 4, 6, 8)
Reduce
Reduce
val data = Seq.range(1, 5)

val data2 = data.reduce(_+_)

val data3 = data.reduce { (v1, v2) =>

println( (v1, v2) )

v1 + v2

}
data: Seq[Int] = List(1, 2, 3, 4)
data2: Int = 10
(1,2)
(3,3)
(6,4)
data3: Int = 10
PRACTICE
• 看懂第⼀個 Spark scala sample code 使⽤的語法
• SparkPi.scala
CLASS
// Scala

// Both getter and setter

class Student1(var name: String)



// Only getter

class Student2(val name: String)



// private

class Student3(val name: String, private val
id: Int)

CASE CLASS
• 同時建⽴ class 與 object
• 為 class 建⽴ getter & setter
• 為 object 建⽴ apply & unapply method
case class Student(val id: Int, val name:
String)



val s = Student(100, "Vito")

Student.unapply(s)
Pattern Matching
• 第⼀眼看起來很像 switch...case...
val b = true

b match {

case true => println("true")

case false => println("false")

}

Pattern Matching
• 實際與 switch 差很⼤, example: Source
class extends & with
• Scala 沒有 Java 的 interface
• Trait - 結合 interface 與 class
class Person {}

trait PlayGame {}

trait ReadBook {}


class Student extends Person
with PlayGame with ReadBook {

}


class LittleBoy extends Person with PlayGame {

}
Sample Code - RDDRelation
SBT
• The interactive build tool, run task from shell
• Installing sbt
• Spark
• Maven is recommented for packaging Spark
• SBT is supported for day-to-day development
SBT
• Commands
• run, run-main
• test, testOnly
• compile
• reload
• 威⼒強⼤的 ~
• Demo
SCALA 實務
• Scala 還蠻難的
• 直接使⽤ Java SDK & 第三⽅ Libraries
• SBT project 可混合 Java & Scala
• 好的 IDE 帶你快速上路: Intellij IDEA
• Spark 是分散式的 Scala
SCALA 實務
• Build tool: recommand SBT
• Testing: Scalatest, Specs2, JUnit
• SBT PermGen space resolve
• http://www.scala-sbt.org/0.13/docs/Manual-Installation.html
• Book
Thank you
and
Question ?

More Related Content

What's hot

Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesTomer Gabel
 
Ankara Jug - Practical Functional Programming with Scala
Ankara Jug - Practical Functional Programming with ScalaAnkara Jug - Practical Functional Programming with Scala
Ankara Jug - Practical Functional Programming with ScalaEnsar Basri Kahveci
 
Metaprogramming in Scala 2.10, Eugene Burmako,
Metaprogramming  in Scala 2.10, Eugene Burmako, Metaprogramming  in Scala 2.10, Eugene Burmako,
Metaprogramming in Scala 2.10, Eugene Burmako, Vasil Remeniuk
 
RESTful API using scalaz (3)
RESTful API using scalaz (3)RESTful API using scalaz (3)
RESTful API using scalaz (3)Yeshwanth Kumar
 
The Design of the Scalaz 8 Effect System
The Design of the Scalaz 8 Effect SystemThe Design of the Scalaz 8 Effect System
The Design of the Scalaz 8 Effect SystemJohn De Goes
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class PatternsJohn De Goes
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Leonardo Borges
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java ProgrammersEric Pederson
 
Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScriptLuis Atencio
 
SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.Ruslan Shevchenko
 
scala.reflect, Eugene Burmako
scala.reflect, Eugene Burmakoscala.reflect, Eugene Burmako
scala.reflect, Eugene BurmakoVasil Remeniuk
 
Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6Nilesh Jayanandana
 

What's hot (20)

Scala Intro
Scala IntroScala Intro
Scala Intro
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
 
Ankara Jug - Practical Functional Programming with Scala
Ankara Jug - Practical Functional Programming with ScalaAnkara Jug - Practical Functional Programming with Scala
Ankara Jug - Practical Functional Programming with Scala
 
Metaprogramming in Scala 2.10, Eugene Burmako,
Metaprogramming  in Scala 2.10, Eugene Burmako, Metaprogramming  in Scala 2.10, Eugene Burmako,
Metaprogramming in Scala 2.10, Eugene Burmako,
 
Scala fundamentals
Scala fundamentalsScala fundamentals
Scala fundamentals
 
RESTful API using scalaz (3)
RESTful API using scalaz (3)RESTful API using scalaz (3)
RESTful API using scalaz (3)
 
The Design of the Scalaz 8 Effect System
The Design of the Scalaz 8 Effect SystemThe Design of the Scalaz 8 Effect System
The Design of the Scalaz 8 Effect System
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class Patterns
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
 
Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScript
 
Workshop Scala
Workshop ScalaWorkshop Scala
Workshop Scala
 
SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.
 
scala.reflect, Eugene Burmako
scala.reflect, Eugene Burmakoscala.reflect, Eugene Burmako
scala.reflect, Eugene Burmako
 
Scala 2013 review
Scala 2013 reviewScala 2013 review
Scala 2013 review
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
 
Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6
 
Scala
ScalaScala
Scala
 

Viewers also liked

Strata Beijing - Deep Learning in Production on Spark
Strata Beijing - Deep Learning in Production on SparkStrata Beijing - Deep Learning in Production on Spark
Strata Beijing - Deep Learning in Production on SparkAdam Gibson
 
唯品会大数据实践 Sacc pub
唯品会大数据实践 Sacc pub唯品会大数据实践 Sacc pub
唯品会大数据实践 Sacc pubChao Zhu
 
Track A-1: Cloudera 大數據產品和技術最前沿資訊報告
Track A-1: Cloudera 大數據產品和技術最前沿資訊報告Track A-1: Cloudera 大數據產品和技術最前沿資訊報告
Track A-1: Cloudera 大數據產品和技術最前沿資訊報告Etu Solution
 
大數據運算媒體業案例分享 (Big Data Compute Case Sharing for Media Industry)
大數據運算媒體業案例分享 (Big Data Compute Case Sharing for Media Industry)大數據運算媒體業案例分享 (Big Data Compute Case Sharing for Media Industry)
大數據運算媒體業案例分享 (Big Data Compute Case Sharing for Media Industry)Amazon Web Services
 
Cloudera 助力台灣大數據產業的發展
Cloudera 助力台灣大數據產業的發展Cloudera 助力台灣大數據產業的發展
Cloudera 助力台灣大數據產業的發展Etu Solution
 
Track A-2 基於 Spark 的數據分析
Track A-2 基於 Spark 的數據分析Track A-2 基於 Spark 的數據分析
Track A-2 基於 Spark 的數據分析Etu Solution
 
翻轉醫療-人類基因大數據解密
翻轉醫療-人類基因大數據解密翻轉醫療-人類基因大數據解密
翻轉醫療-人類基因大數據解密Chung-Tsai Su
 
Hadoop, the Apple of Our Eyes (這些年,我們一起追的 Hadoop)
Hadoop, the Apple of Our Eyes (這些年,我們一起追的 Hadoop)Hadoop, the Apple of Our Eyes (這些年,我們一起追的 Hadoop)
Hadoop, the Apple of Our Eyes (這些年,我們一起追的 Hadoop)Kuo-Chun Su
 
Track B-3 解構大數據架構 - 大數據系統的伺服器與網路資源規劃
Track B-3 解構大數據架構 - 大數據系統的伺服器與網路資源規劃Track B-3 解構大數據架構 - 大數據系統的伺服器與網路資源規劃
Track B-3 解構大數據架構 - 大數據系統的伺服器與網路資源規劃Etu Solution
 
基于Hbase的实时计算分享
基于Hbase的实时计算分享基于Hbase的实时计算分享
基于Hbase的实时计算分享yiihsia
 
基于hbase的实时计算框架prom(20111114)
基于hbase的实时计算框架prom(20111114)基于hbase的实时计算框架prom(20111114)
基于hbase的实时计算框架prom(20111114)yiihsia
 
100景文科大碩士招生簡章(公告)
100景文科大碩士招生簡章(公告)100景文科大碩士招生簡章(公告)
100景文科大碩士招生簡章(公告)景文 CIID
 
Stockflare 强大的股票筛选工具嘉维证券合作伙伴独享
Stockflare 强大的股票筛选工具嘉维证券合作伙伴独享Stockflare 强大的股票筛选工具嘉维证券合作伙伴独享
Stockflare 强大的股票筛选工具嘉维证券合作伙伴独享Shane Leonard, CFA
 
Integrating data stored in rdbms and hadoop
Integrating data stored in rdbms and hadoopIntegrating data stored in rdbms and hadoop
Integrating data stored in rdbms and hadoopleorick lin
 
敏捷开发技术最佳实践(统一敏捷开发过程)
敏捷开发技术最佳实践(统一敏捷开发过程)敏捷开发技术最佳实践(统一敏捷开发过程)
敏捷开发技术最佳实践(统一敏捷开发过程)Weijun Zhong
 
Cassandra 2.1 簡介
Cassandra 2.1 簡介Cassandra 2.1 簡介
Cassandra 2.1 簡介Cloud Tu
 
不断归零的前端人生 - 2016 中国软件开发者大会
不断归零的前端人生 - 2016 中国软件开发者大会不断归零的前端人生 - 2016 中国软件开发者大会
不断归零的前端人生 - 2016 中国软件开发者大会Joseph Chiang
 

Viewers also liked (20)

Strata Beijing - Deep Learning in Production on Spark
Strata Beijing - Deep Learning in Production on SparkStrata Beijing - Deep Learning in Production on Spark
Strata Beijing - Deep Learning in Production on Spark
 
唯品会大数据实践 Sacc pub
唯品会大数据实践 Sacc pub唯品会大数据实践 Sacc pub
唯品会大数据实践 Sacc pub
 
Track A-1: Cloudera 大數據產品和技術最前沿資訊報告
Track A-1: Cloudera 大數據產品和技術最前沿資訊報告Track A-1: Cloudera 大數據產品和技術最前沿資訊報告
Track A-1: Cloudera 大數據產品和技術最前沿資訊報告
 
大數據運算媒體業案例分享 (Big Data Compute Case Sharing for Media Industry)
大數據運算媒體業案例分享 (Big Data Compute Case Sharing for Media Industry)大數據運算媒體業案例分享 (Big Data Compute Case Sharing for Media Industry)
大數據運算媒體業案例分享 (Big Data Compute Case Sharing for Media Industry)
 
Cloudera 助力台灣大數據產業的發展
Cloudera 助力台灣大數據產業的發展Cloudera 助力台灣大數據產業的發展
Cloudera 助力台灣大數據產業的發展
 
Track A-2 基於 Spark 的數據分析
Track A-2 基於 Spark 的數據分析Track A-2 基於 Spark 的數據分析
Track A-2 基於 Spark 的數據分析
 
翻轉醫療-人類基因大數據解密
翻轉醫療-人類基因大數據解密翻轉醫療-人類基因大數據解密
翻轉醫療-人類基因大數據解密
 
Hadoop, the Apple of Our Eyes (這些年,我們一起追的 Hadoop)
Hadoop, the Apple of Our Eyes (這些年,我們一起追的 Hadoop)Hadoop, the Apple of Our Eyes (這些年,我們一起追的 Hadoop)
Hadoop, the Apple of Our Eyes (這些年,我們一起追的 Hadoop)
 
Track B-3 解構大數據架構 - 大數據系統的伺服器與網路資源規劃
Track B-3 解構大數據架構 - 大數據系統的伺服器與網路資源規劃Track B-3 解構大數據架構 - 大數據系統的伺服器與網路資源規劃
Track B-3 解構大數據架構 - 大數據系統的伺服器與網路資源規劃
 
基于Hbase的实时计算分享
基于Hbase的实时计算分享基于Hbase的实时计算分享
基于Hbase的实时计算分享
 
Xapian介绍
Xapian介绍Xapian介绍
Xapian介绍
 
基于hbase的实时计算框架prom(20111114)
基于hbase的实时计算框架prom(20111114)基于hbase的实时计算框架prom(20111114)
基于hbase的实时计算框架prom(20111114)
 
100景文科大碩士招生簡章(公告)
100景文科大碩士招生簡章(公告)100景文科大碩士招生簡章(公告)
100景文科大碩士招生簡章(公告)
 
Smart library
Smart librarySmart library
Smart library
 
Stockflare 强大的股票筛选工具嘉维证券合作伙伴独享
Stockflare 强大的股票筛选工具嘉维证券合作伙伴独享Stockflare 强大的股票筛选工具嘉维证券合作伙伴独享
Stockflare 强大的股票筛选工具嘉维证券合作伙伴独享
 
Integrating data stored in rdbms and hadoop
Integrating data stored in rdbms and hadoopIntegrating data stored in rdbms and hadoop
Integrating data stored in rdbms and hadoop
 
敏捷开发技术最佳实践(统一敏捷开发过程)
敏捷开发技术最佳实践(统一敏捷开发过程)敏捷开发技术最佳实践(统一敏捷开发过程)
敏捷开发技术最佳实践(统一敏捷开发过程)
 
Cassandra 2.1 簡介
Cassandra 2.1 簡介Cassandra 2.1 簡介
Cassandra 2.1 簡介
 
創作型論文
創作型論文創作型論文
創作型論文
 
不断归零的前端人生 - 2016 中国软件开发者大会
不断归零的前端人生 - 2016 中国软件开发者大会不断归零的前端人生 - 2016 中国软件开发者大会
不断归零的前端人生 - 2016 中国软件开发者大会
 

Similar to Scala introduction

Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghStuart Roebuck
 
Spark Summit EU talk by Ted Malaska
Spark Summit EU talk by Ted MalaskaSpark Summit EU talk by Ted Malaska
Spark Summit EU talk by Ted MalaskaSpark Summit
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scalaXing
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?Tomasz Wrobel
 
Introduction aux Macros
Introduction aux MacrosIntroduction aux Macros
Introduction aux Macrosunivalence
 
楽々Scalaプログラミング
楽々Scalaプログラミング楽々Scalaプログラミング
楽々ScalaプログラミングTomoharu ASAMI
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scalashinolajla
 
An Introduction to Higher Order Functions in Spark SQL with Herman van Hovell
An Introduction to Higher Order Functions in Spark SQL with Herman van HovellAn Introduction to Higher Order Functions in Spark SQL with Herman van Hovell
An Introduction to Higher Order Functions in Spark SQL with Herman van HovellDatabricks
 
Compact and safely: static DSL on Kotlin
Compact and safely: static DSL on KotlinCompact and safely: static DSL on Kotlin
Compact and safely: static DSL on KotlinDmitry Pranchuk
 
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017 Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017 Codemotion
 
Intro to Scala.js - Scala UG Cologne
Intro to Scala.js - Scala UG CologneIntro to Scala.js - Scala UG Cologne
Intro to Scala.js - Scala UG CologneMarius Soutier
 
MiamiJS - The Future of JavaScript
MiamiJS - The Future of JavaScriptMiamiJS - The Future of JavaScript
MiamiJS - The Future of JavaScriptCaridy Patino
 
Emerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonEmerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonAlex Payne
 
Scala 生态圈 (scala ecosystem)
Scala 生态圈 (scala ecosystem)Scala 生态圈 (scala ecosystem)
Scala 生态圈 (scala ecosystem)max peng
 

Similar to Scala introduction (20)

Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
Spark Summit EU talk by Ted Malaska
Spark Summit EU talk by Ted MalaskaSpark Summit EU talk by Ted Malaska
Spark Summit EU talk by Ted Malaska
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 
Introduction aux Macros
Introduction aux MacrosIntroduction aux Macros
Introduction aux Macros
 
楽々Scalaプログラミング
楽々Scalaプログラミング楽々Scalaプログラミング
楽々Scalaプログラミング
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
 
A bit about Scala
A bit about ScalaA bit about Scala
A bit about Scala
 
Command Liner with Scala
Command Liner with ScalaCommand Liner with Scala
Command Liner with Scala
 
Scala on Android
Scala on AndroidScala on Android
Scala on Android
 
An Introduction to Higher Order Functions in Spark SQL with Herman van Hovell
An Introduction to Higher Order Functions in Spark SQL with Herman van HovellAn Introduction to Higher Order Functions in Spark SQL with Herman van Hovell
An Introduction to Higher Order Functions in Spark SQL with Herman van Hovell
 
Hello scala
Hello scalaHello scala
Hello scala
 
Scala intro workshop
Scala intro workshopScala intro workshop
Scala intro workshop
 
Compact and safely: static DSL on Kotlin
Compact and safely: static DSL on KotlinCompact and safely: static DSL on Kotlin
Compact and safely: static DSL on Kotlin
 
Scala active record
Scala active recordScala active record
Scala active record
 
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017 Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
 
Intro to Scala.js - Scala UG Cologne
Intro to Scala.js - Scala UG CologneIntro to Scala.js - Scala UG Cologne
Intro to Scala.js - Scala UG Cologne
 
MiamiJS - The Future of JavaScript
MiamiJS - The Future of JavaScriptMiamiJS - The Future of JavaScript
MiamiJS - The Future of JavaScript
 
Emerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonEmerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the Horizon
 
Scala 生态圈 (scala ecosystem)
Scala 生态圈 (scala ecosystem)Scala 生态圈 (scala ecosystem)
Scala 生态圈 (scala ecosystem)
 

More from vito jeng

Quill - 一個 Scala 的資料庫存取利器
Quill - 一個 Scala 的資料庫存取利器Quill - 一個 Scala 的資料庫存取利器
Quill - 一個 Scala 的資料庫存取利器vito jeng
 
Scala fun part: Reflection(runtime)
Scala fun part: Reflection(runtime)Scala fun part: Reflection(runtime)
Scala fun part: Reflection(runtime)vito jeng
 
Intellij IDEA Intro, Tips and Tricks
Intellij IDEA Intro, Tips and TricksIntellij IDEA Intro, Tips and Tricks
Intellij IDEA Intro, Tips and Tricksvito jeng
 
Streaming process with Kafka Connect and Kafka Streams
Streaming process with Kafka Connect and Kafka StreamsStreaming process with Kafka Connect and Kafka Streams
Streaming process with Kafka Connect and Kafka Streamsvito jeng
 
ScalaMatsuri 2017 Note
ScalaMatsuri 2017 NoteScalaMatsuri 2017 Note
ScalaMatsuri 2017 Notevito jeng
 
The SparkSQL things you maybe confuse
The SparkSQL things you maybe confuseThe SparkSQL things you maybe confuse
The SparkSQL things you maybe confusevito jeng
 

More from vito jeng (6)

Quill - 一個 Scala 的資料庫存取利器
Quill - 一個 Scala 的資料庫存取利器Quill - 一個 Scala 的資料庫存取利器
Quill - 一個 Scala 的資料庫存取利器
 
Scala fun part: Reflection(runtime)
Scala fun part: Reflection(runtime)Scala fun part: Reflection(runtime)
Scala fun part: Reflection(runtime)
 
Intellij IDEA Intro, Tips and Tricks
Intellij IDEA Intro, Tips and TricksIntellij IDEA Intro, Tips and Tricks
Intellij IDEA Intro, Tips and Tricks
 
Streaming process with Kafka Connect and Kafka Streams
Streaming process with Kafka Connect and Kafka StreamsStreaming process with Kafka Connect and Kafka Streams
Streaming process with Kafka Connect and Kafka Streams
 
ScalaMatsuri 2017 Note
ScalaMatsuri 2017 NoteScalaMatsuri 2017 Note
ScalaMatsuri 2017 Note
 
The SparkSQL things you maybe confuse
The SparkSQL things you maybe confuseThe SparkSQL things you maybe confuse
The SparkSQL things you maybe confuse
 

Recently uploaded

cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 

Recently uploaded (20)

cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 

Scala introduction

  • 2. WHO AM I • 鄭紹志 • IS-LAND Technical Manager • HareDB • Hadoop + HBase • Scala + Spark
  • 3. WHY SCALA WHY NOT SCALA • Scala - The good, the bad and the very ugly • http://www.slideshare.net/Bozho/scala-the-good-the-bad-and-the-very-ugly •Why Scala • http://www.slideshare.net/al3x/why-scala-presentation •Today Gist: http://tinyurl.com/z8xx6ab
  • 4. SCALABLE LANGUAGE • Runs on JVM • Concise, 簡潔 • Statically typed, 靜態型別 • Object Oriented Programming, 物件導向開發 • Functional Programming, 函數式開發
  • 5. Sample Code - SparkPi
  • 6.
  • 7. SCALA INSTALL • Scala 2.10.x - Spark 1.0 - 1.6 都使⽤ 2.10.x • Download Scala 2.10.x • http://www.scala-lang.org/download/all.html • 解壓縮 & 設定路徑 • http://www.scala-lang.org/download/install.html
  • 8. SCALA INTERPRETER • scala: Read-Evaluate-Print-Loop(REPL) [~]$ scala Welcome to Scala version 2.11.7 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_80). Type in expressions to have them evaluated. Type :help for more information. scala> val name = "Vito" name: String = Vito scala> println( s"Hello, $name" ) Hello, Vito scala> println( name.getClass ) class java.lang.String scala>
  • 9. SCALA INTERPRETER • One line execute • Run script • Run main class • Shell script • Load file: :load • Paste mode: :paste $ scala -e 'val name="Vito"; println(s"Hello,$name")' $ scala hello.scala $ scala HelloWorld.scala $ ./script.sh
  • 10. Value & Variable • 定義常數與變數 • 優先考慮使⽤ val var price1 = 100
 price1 = 200
 
 val price2 = 100
 price2 = 200 // error: reassignment to val
  • 11. Type Inference • 推斷使⽤的型別 val name = "Vito"
 val n1 = 100
 val n2 = 100L
 val n3: Int = 100
 
 val n4 = 20.6F
 val list = Seq("a", "b", "c")
 
 import java.util._
 val list1 = new ArrayList[String]()
  • 12. STRING // 
 val s1 = "Hello"
 // 
 val s2 = """object HelloWorld extends App {
 println("Hello, World!")
 }
 """
 // string interpolation
 val s3 = s"[$s1] source code:n$s2"
 
 // no escape
 val s4 = raw"Hello n world."
 val s5 = "Hello"(1)
 val s6 = "Hello".charAt(1)
  • 13. TUPLE • Tuple2 - Tuple22 val t2a = ("a", 2)
 val t2b = Tuple2("a", 2)
 val t2c = new Tuple2("a", 2)
 val t2d = "a" -> 2
 val t5 = ("a", 100, "c", 20.5, (1,2,3))
 
 val v1 = t2a._1 == t2a._1 // true
 val v2 = t5._5 == (1,2,3) // true
  • 14. OBJECT ORIENTED // 
 // . ( )
 "Hello World" split " "
 "Hello World".split(" ")
 
 // operator 
 "a" + "b" + "c"
 "a".+("b").+("c")
  • 15. IMPORT CLASS • 預設 import • java.lang._ • scala._ • Java *, Scala _ • scala.Predef object import java.util._
 import java.util.{List, ArrayList} import java.util.{List=>JList, HashMap=>JHashMap} import java.util.{Date=>_, _}
  • 16. IMPORT CLASS • Import anywhere import org.apache.spark.{SparkContext, SparkConf, Logging} class MyClass {
 import java.util._
 def printDate() = {
 val date = new Date()
 println(date)
 }
 def printFilePath() = {
 import java.io.File
 val file = new File("data.txt")
 println(file.getAbsolutePath)
 }
 }
  • 17. OBJECT • Scala 沒有 Java 的 static 宣告, 可⽤ object 代替 • 想⽤ Singletion pattern 就⽤ object • Companion Objects: 同名的 class 與 object 同時 存在 object Student {
 def sayHi = println("Hi~")
 }
 Student.sayHi
  • 18. OBJECT class Student(val name: String) {
 override def toString = s"[Student]: $name"
 }
 
 object Student {
 def apply(names: String*) = {
 names.map { n => new Student(n) }
 }
 def count(ss: Seq[Student]) = ss.size
 }
 
 val ss = Student("Vito", "John")
 Student.count(ss)
  • 19. RETURN VALUE • method 傳回值不須加 return • Every statement(expression) yields a value val a = 5
 val b = if (a>2) 0 else 1
 val data = Seq(1,2,3,4,5)
 val data1 = for (
 num <- data
 if num % 2 == 0
 ) yield {
 num + 10
 } // data1: List(12, 14)
  • 20. RETURN VALUE • Every statement(expression) yields a value def calc(a: Int, b: Int) = try {
 a / b
 } catch {
 case _: Throwable => 0
 }
 
 val a = calc(100, 0) calc: (a: Int, b: Int)Int a: Int = 0
  • 21. Anonymous Functions val data = Seq.range(1, 5)
 val data2 = data.map( (s: Int) => s*2 )
 val data3 = data.map( (s) => s*2 )
 val data4 = data.map( _*2 ) data: Seq[Int] = List(1, 2, 3, 4) data2: Seq[Int] = List(2, 4, 6, 8) data3: Seq[Int] = List(2, 4, 6, 8) data4: Seq[Int] = List(2, 4, 6, 8)
  • 22. Anonymous Functions val data = Seq.range(1, 5)
 val multi = (s: Int) => s * 2
 val multi2 = new Function1[Int, Int]() {
 override def apply(v1: Int): Int = v1 * 2
 }
 val data2 = data.map(multi)
 val data3 = data map multi
 val data4 = data map multi2 multi: Int => Int = <function1> multi2: Int => Int = <function1> data2: Seq[Int] = List(2, 4, 6, 8) data3: Seq[Int] = List(2, 4, 6, 8) data4: Seq[Int] = List(2, 4, 6, 8)
  • 23. Function ? Method ? • ⽬前不必追究 • (想追究的😆)可從這裡先開始, 再 Google • http://stackoverflow.com/q/2529184
  • 24. map
  • 25. map val data = Seq.range(1, 5)
 val multi = (s: Int) => s * 2
 val data2 = data.map( _*2 )
 val data3 = data map multi
 data: Seq[Int] = List(1, 2, 3, 4) multi: Int => Int = <function1> data2: Seq[Int] = List(2, 4, 6, 8) data3: Seq[Int] = List(2, 4, 6, 8)
  • 27. Reduce val data = Seq.range(1, 5)
 val data2 = data.reduce(_+_)
 val data3 = data.reduce { (v1, v2) =>
 println( (v1, v2) )
 v1 + v2
 } data: Seq[Int] = List(1, 2, 3, 4) data2: Int = 10 (1,2) (3,3) (6,4) data3: Int = 10
  • 28. PRACTICE • 看懂第⼀個 Spark scala sample code 使⽤的語法 • SparkPi.scala
  • 29.
  • 30. CLASS // Scala
 // Both getter and setter
 class Student1(var name: String)
 
 // Only getter
 class Student2(val name: String)
 
 // private
 class Student3(val name: String, private val id: Int)

  • 31. CASE CLASS • 同時建⽴ class 與 object • 為 class 建⽴ getter & setter • 為 object 建⽴ apply & unapply method case class Student(val id: Int, val name: String)
 
 val s = Student(100, "Vito")
 Student.unapply(s)
  • 32. Pattern Matching • 第⼀眼看起來很像 switch...case... val b = true
 b match {
 case true => println("true")
 case false => println("false")
 }

  • 33. Pattern Matching • 實際與 switch 差很⼤, example: Source
  • 34. class extends & with • Scala 沒有 Java 的 interface • Trait - 結合 interface 與 class class Person {}
 trait PlayGame {}
 trait ReadBook {} 
 class Student extends Person with PlayGame with ReadBook {
 } 
 class LittleBoy extends Person with PlayGame {
 }
  • 35. Sample Code - RDDRelation
  • 36. SBT • The interactive build tool, run task from shell • Installing sbt • Spark • Maven is recommented for packaging Spark • SBT is supported for day-to-day development
  • 37. SBT • Commands • run, run-main • test, testOnly • compile • reload • 威⼒強⼤的 ~ • Demo
  • 38. SCALA 實務 • Scala 還蠻難的 • 直接使⽤ Java SDK & 第三⽅ Libraries • SBT project 可混合 Java & Scala • 好的 IDE 帶你快速上路: Intellij IDEA • Spark 是分散式的 Scala
  • 39. SCALA 實務 • Build tool: recommand SBT • Testing: Scalatest, Specs2, JUnit • SBT PermGen space resolve • http://www.scala-sbt.org/0.13/docs/Manual-Installation.html • Book