SlideShare a Scribd company logo
Why Scala?
JBoss Users Club 윤재진
Reason 1
Concurrency
CPU의 변화
CPU 속도의 증가는 느려짐
2001년 IBM에서 PowerPC 4 멀티코어 도입
업체들이 CPU 속도보다 코어수를 늘리기 시작함
2007년경 AMD에서 먼저 쿼드코어 CPU 발매
현재는???
CPU의 변화
현재는??
그래픽 카드도 듀얼코어
핸드폰도 듀얼코어
노트북은 쿼드코어
개발자는 어떻게 대처를??
Concurrency Programming
cpu 변화에 따른 우리는?
multi core로만 성능이 향상되지는 않는다	
multi core에 맞게 프로그래밍이 되어야지 성능
이 향상이 될 수 있다.	
우리는 이에 맞는 프로그래밍을 해야 한다.	
현재는 하지 않아도 앞으로 하게 될지 모른다.
Concurrency
다행히도 자바에선 Concurrency가 언어 자체에서
지원	
synchronized	
AtomicInteger 등 자바자체적으로 지원 기능이
많음
Thread t1 = new Thread (new Runnable() {
public void run() { while(true) { System.out.println("tic"); }}
});
Thread t2 = new Thread (new Runnable() {
public void run() { while(true) { System.out.println("toc"); }}
});
!
t1.start(); t2.start();
!
Listing 1: Parallel Threads in Java
Thread t1 = new Thread (new Runnable() {
public void run() { while(true) { System.out.println("tic"); }}
});
Thread t2 = new Thread (new Runnable() {
public void run() { while(true) { System.out.println("toc"); }}
});
!
t1.start(); t2.start();
!
Listing 2: Pooled Parallel Threading in Java
import java.util.concurrent.atomic.AtomicInteger;
!
public class AtomicCounter {
AtomicInteger ctr = new AtomicInteger(0);
public void Increment(int k) { ctr.addAndGet(k); }
public void Decrement(int k) { ctr.addAndGet(-k); }
}
Listing 4: Atomic Increment
public class Counter {
private int ctr = 0;
public synchronized void Increment(int k) { ctr += k; }
public synchronized void Decrement(int k) { ctr -= k; }
}
Listing 3:Synchronized Updates
하지만???
기본적으로 고려해야할 점은???
Shared Memory
잘못하게 되면??
Dead lock
조금만 더 쉽게 개발은 할 수 없는걸까????
Shared Memory 사용하지 않고 개발
Shared Memory 사용않고 개발은?
Functional language 사용	
erlang : Actor 	
erjang : jvm 위에서 사용하는 erlang	
clojure : jvm, .net에서 돌아가는 lisp	
scala : scalable 라고 jvm,.net에 돌아
감
Reason 2
지식	 자산을	 얻는	 최선의	 길은	 
무엇일까?
지식	 자산을	 얻는	 최선의	 
길은	 무엇일까?
매년 새로운 언어을 최소 하나는 배워라	
기술서적을 분기마다 한권씩 읽어라	
비기술 서적도 읽어라	
수업을 들어라	
지역 사용자 모임에 참여라하	
다른환경에서 사용하라	
요즘 흐름을 놓치리 마라	
인터넷을 이용하라
Reason 3
“If I were to pick a language to use today other than Java, it
would be Scala”	

James Gosling
What is Scala?
Scalable Language !
Grow the Library not the Syntax
Scalable Language
에릭 레이몬드가 이야기 했던 성장과 시장 모델에서
시장 모델을 추구함	
이미 만들어진 라이브러말고 사용자가 쓰면서 필요한
부분을 오픈소스로 계속 추가하도록 하는게 목적 	
그래서 Scalable Language라 함
OO+ FP
ㅋ!
Martin Odersky
Since 2003 Sponsored by EPFL
Pragmatic
Runs on the JVM
Statically typed
Growing new types
Seamless integration with Java
Concise
// Java	
public class Person { 	
private String name; 	
private int age; 	
public Person(String name,	
int age) 	
{ 	
this.name = name;	
this.age = age;	
}	
public String getName() {	
return name; 	
}	
public int getAge() {	
return age;	
}	
public void setName(String
name) {	
this.name = name;	
}}	
// Scala	
class Person( var name:
String, var age: Int)
Pure OO
1 + 2
1.+(2)
123.toString()
모든것들은 객체
Pragmatic
val joe =
<employee	
name="Joe"	
rank="code
monkey"	
serial="123"
/>
XML 선언
scala> joe  "@name"	
res15: scala.xml.NodeSeq = Joe	
!
scala> joe  "@serial"	
res16: scala.xml.NodeSeq = 123
추출
Scala high level
// this is Java 	
boolean nameHasUpperCase = false; 	
for (int i = 0; i < name.length(); ++i) {	
if (Character.isUpperCase(name.charAt(i))) 	
{ 	
nameHasUpperCase = true; break;	
}	
}
val nameHasUpperCase = name.exists(_.isUpper)
Scala’s root
많은 언어들에서 영향을 받음	
문법은 기본적으로 Java, C#을 채용함	
Convention은 C,C++에 빌려옴	
Object models 기본적으로 Smalltalk, 부분
적으로 Ruby	
Actor models은 erlang
자세히 들어가 보자
변수 선언
val msg = “Hello, World!”
var msg2 = “Hello, World!”
val : FP 형태의 immutable 선언방식
var : Java 형태의 mutable 선언방식
함수 선언
def max(x: Int, y: Int): Int =
{ 	
if (x > y) x	
else y	
}
def max2(x: Int, y: Int) = if
(x > y) x else y
class
class Person( var name: String, var age: Int)
class ChecksumAccumulator { 	
// class definition goes here	
}
class Person( var name: String, var age: Int) {	
var name:String = name;	
var age: Int = age;	
}
val person = new Person(“jaejin”,30)	
val checksum = new ChecksumAccumulator
object
싱글톤 클래스	
scala에서는 static type이 없어서 object을
이용하거나 import로 static을 대신할 수 있다.	
사용방법은 똑같은 이름의 class가 같은 scala
파일에 있어야 한다.	
class와 똑같은 명칭의 object을 선언하면 사용
할 수 있다.
object
object SingleObject {	
def printSingle(a:String) {	
print(a)	
}	
}
scala> val t = SingleObject	
scala> t.print(“test”)	
test	
scala> SingleObject.print(“test”)
Companion object
// In file ChecksumAccumulator.scala!
class ChecksumAccumulator { !
private var sum = 0 !
def add(b: Byte) { sum += b } !
def checksum(): Int = ~(sum & 0xFF) + 1!
}
// In file ChecksumAccumulator.scala	
import scala.collection.mutable.Map 	
object ChecksumAccumulator {	
private val cache = Map[String, Int]()	
def calculate(s: String): Int = 	
if (cache.contains(s))	
cache(s) 	
else {	
val acc = new ChecksumAccumulator 	
for (c <- s)	
acc.add(c.toByte) 	
val cs = acc.checksum() 	
cache += (s -> cs) 	
cs	
}	
}
expression
var filename = "default.txt" !
if (!args.isEmpty)!
filename = args(0)
val filename = !
if (!args.isEmpty) args(0) !
else "default.txt"
for (i <- 1 to 4) !
println("Iteration "+ i)
val filesHere = (new java.io.File(".")).listFiles !
for (file <- filesHere if file.getName.endsWith(".scala"))!
println(file)
trait
Rich interface	
멤버선언이 가능	
abstract 메소드 선언 가능	
메소드 구현 가능
trait Dad { 	
private var children: List[Child] = Nil	
!
def addChild(child: Child) = 	
children = child :: children	
!
def getChildren = children.clone	
}
trait
class Man(val name: String) extends Human	
class Child(val name: String) extends Human
Base
class Human
Static mixin composition
class Man(val name: String) extends Human with Dad
uasage
val sanghun = new Man(“상훈”) 	
sanghun.addChild(new Child(“원희”))
Dynamic mixin composition
class Man(val name: String) extends Human
uasage
val sanghun = new Man(“상훈”) with Dad	
sanghun.addChild(new Child(“원희”))
Stackable
modifications
trait IgnoreCaseSet extends java.util.Set[String] {	
!
abstract override def add(e: String) = { 	
super.add(e.toLowerCase)	
} 	
	
abstract override def contains(e: String) = {	
super.contains(e.toLowerCase) 	
} 	
	
abstract override def remove(e: String) = {	
super.remove(e.toLowerCase)	
}	
}
Stackable
modifications
val set = new java.util.HashSet[String]
with IgnoreCaseSet	
set.add(“HI THERE“)	 // uppercase	
set.contains(“hi there“) // lowercase	
=> true
Stackable
modifications
trait LoggableSet extends java.util.Set[String] {	
!
abstract override def add(e: String) = 	
{ 	
println(“Add :“ + e) 	
super.add(e)	
}	
	
abstract override def remove(e: String) = { 	
println(“Remove :“ + e) 	
super.remove(e) 	
}	
}
Stackable
modifications
val set = new java.util.HashSet[String] 	
with IgnoreCaseSet 	
with LoggableSet	
set.add(“HI THERE“) 	
=> “Add: HI THERE”
Stackable
modifications
val set = new java.util.HashSet[String] 	
with LoggableSet	
with IgnoreCaseSet 	
set.add(“HI THERE“) 	
=> “Add: hi there”
package, import
static import 제공	
import java.lang._	
import java.lang.Integer._	
package 안에 패키지 가능	
접근자 없으면 public	
protected는 사용만 가능하고 패키지에서 접근 불가능
Functional
programming
Pure function	
first-class and higher-order	
Recursion
first-class
def square(x: Int): Int = x * x
def sumInts(a: Int, b: Int): Int = if (a >
b) 0 else a + sumInts(a + 1, b)
FP
val inc = (x: Int) => x + 1
scala> inc(1)
2
FP - higher order
List(1, 2, 3).map((x: Int) => x + 1)
List(2,3,4)
currying
def sum(f: Int => Int): (Int, Int) => Int = { !
def sumF(a: Int, b: Int): Int =!
if (a > b) 0 else f(a) + sumF(a + 1, b) !
sumF!
}
scala> sum(x=>x*x)(1,10)
result : Int = 385
currying-tail
def sum(f: Int => Int)(a: Int, b: Int): Int = { !
def iter(a: Int, result: Int): Int = {!
if (a>b) result else iter(a+1, f(a)+result)!
iter(a, 0)!
}
scala> sum(x=>x*x)(1,10)
result : Int = 385
List 만들기
val list = List(1,2,3)	
val list2= 1 :: 2 :: 3 :: Nil	
val list3 = List(1) ::: List(2) ::: List(3)	
val list4 = 1 :: (2 :: (3 :: Nil))	
list == list2 ==list3 == list4	
=> true
List 이해
val list = List(1,2,3)	
list.head == 1 => true	
list.tail == List(2,3) => true	
val head :: tail = List(1,2,3)	
head == 1 => true	
tail == List(2,3) => true
List 이해
val list = List(1, 2, 3)	
list.map(_ + 1) 	
list.filter(_ < 2) 	
list.exists(_ == 3) 	
list.drop(2) 	
list.reverse 	
list.sort(_ > _) 	
List.flatten(list) 	
list.slice(2, 3) 	
...
=> List(2,3,4)
=> List(1)
true
=> List(1,3)
=> List(3,2,1)
=> List(3,2,1)
=> List(1,2,3)
=> List(3)
pattern matching
def matchAny(a: Any): Any = a match {	
case 1 => “one”	
case “two” => 2	
case i: Int => “scala.int”	
case <tag>{ t }</tag> => t	
case head :: tail => head	
case _ => default	
}
xml
abstract class CCTherm { !
val description: String !
val yearMade: Int !
val dateObtained: String !
val bookPrice: Int!// in US cents !
val purchasePrice: Int // in US cents !
val condition: Int! // 1 to 10!
override def toString = description!
def toXML = <cctherm>!
<description>{description}</description> !
<yearMade>{yearMade}</yearMade> !
<dateObtained>{dateObtained}</dateObtained> !
<bookPrice>{bookPrice}</bookPrice> !
<purchasePrice>{purchasePrice}</purchasePrice> !
<condition>{condition}</condition>!
</cctherm>!
}
xml
scala> val therm = new CCTherm { !
val description = "hot dog #5"!
val yearMade = 1952 !
val dateObtained = "March 14, 2006" !
val bookPrice = 2199 !
val purchasePrice = 500 !
val condition = 9!
}!
therm: CCTherm = hot dog #5!
scala> therm.toXML!
res6: scala.xml.Elem = <cctherm>!
<description>hot dog #5</description> !
<yearMade>1952</yearMade> !
<dateObtained>March 14, 2006</dateObtained> !
<bookPrice>2199</bookPrice> !
<purchasePrice>500</purchasePrice> !
<condition>9</condition>!
</cctherm>
actor
val echoActor = actor { !
while (true) { !
receive { !
case msg =>!
println("received message: "+ msg)!
}!
}!
}
actor
scala> echoActor ! "hi there"
received message: hi there!
scala> echoActor ! 15
received message: 15
Q & A
참고자료
http://en.wikipedia.org/wiki/
Functional_programming	
Programming in scala 2th	
example in scala	
http://www.slideshare.net/jboner/pragmatic-real-
world-scala-45-min-presentation	
http://java.sys-con.com/node/419716?page=0,1	
http://drdobbs.com/web-development/184405990?
pgno=2

More Related Content

What's hot (20)

PDF
Realm은 어떻게 효율적인 데이터베이스를 만들었나?
Leonardo YongUk Kim
 
PDF
Collection framework
ssuser34b989
 
PDF
파이썬 기본 문법
SeongHyun Ahn
 
PDF
파이썬 모듈 패키지
SeongHyun Ahn
 
PPTX
엘라스틱서치 분석 이해하기 20160623
Yong Joon Moon
 
PPT
자바야 놀자 PPT
JinKyoungHeo
 
PDF
데이터 분석 3 - Java Collection Framework와 ArrayList
Jaewook Byun
 
PDF
데이터 분석 5 - Java Collection Framework - LinkedList 파헤치기
Jaewook Byun
 
PDF
파이썬 유용한 라이브러리
SeongHyun Ahn
 
PPTX
파이썬+데이터+구조+이해하기 20160311
Yong Joon Moon
 
PDF
데이터 분석 4 - 나만의 배열 기반 LIST, MyArrayList를 만들어보자
Jaewook Byun
 
PPTX
파이썬정리 20160130
Yong Joon Moon
 
PDF
데이터 분석 6 - 나만의 배열 기반 LIST, MyLinkedList를 만들어보자
Jaewook Byun
 
PPTX
파이썬+Json+이해하기 20160301
Yong Joon Moon
 
PPTX
파이썬+Operator+이해하기 20160409
Yong Joon Moon
 
PDF
EcmaScript6(2015) Overview
yongwoo Jeon
 
PPTX
파이썬 namespace Binding 이해하기
Yong Joon Moon
 
PDF
10장 문자열클래스와파일클래스
웅식 전
 
PPTX
Jupyter notebok tensorboard 실행하기_20160706
Yong Joon Moon
 
PDF
안드로이드 개발자를 위한 스위프트
병한 유
 
Realm은 어떻게 효율적인 데이터베이스를 만들었나?
Leonardo YongUk Kim
 
Collection framework
ssuser34b989
 
파이썬 기본 문법
SeongHyun Ahn
 
파이썬 모듈 패키지
SeongHyun Ahn
 
엘라스틱서치 분석 이해하기 20160623
Yong Joon Moon
 
자바야 놀자 PPT
JinKyoungHeo
 
데이터 분석 3 - Java Collection Framework와 ArrayList
Jaewook Byun
 
데이터 분석 5 - Java Collection Framework - LinkedList 파헤치기
Jaewook Byun
 
파이썬 유용한 라이브러리
SeongHyun Ahn
 
파이썬+데이터+구조+이해하기 20160311
Yong Joon Moon
 
데이터 분석 4 - 나만의 배열 기반 LIST, MyArrayList를 만들어보자
Jaewook Byun
 
파이썬정리 20160130
Yong Joon Moon
 
데이터 분석 6 - 나만의 배열 기반 LIST, MyLinkedList를 만들어보자
Jaewook Byun
 
파이썬+Json+이해하기 20160301
Yong Joon Moon
 
파이썬+Operator+이해하기 20160409
Yong Joon Moon
 
EcmaScript6(2015) Overview
yongwoo Jeon
 
파이썬 namespace Binding 이해하기
Yong Joon Moon
 
10장 문자열클래스와파일클래스
웅식 전
 
Jupyter notebok tensorboard 실행하기_20160706
Yong Joon Moon
 
안드로이드 개발자를 위한 스위프트
병한 유
 

Viewers also liked (20)

PPTX
클로저 1
samagu0030
 
PPT
7.데이터수정
Kwang Jung Kim
 
PPT
6.테이블만들기
Kwang Jung Kim
 
PPTX
자연스러운 세부 수준 변화
samagu0030
 
PPTX
실무로 배우는 시스템 성능 최적화 10부. 네트워크 모니터링
Hyunsoo Jung
 
PPTX
픽킹
samagu0030
 
PPTX
Fsm
samagu0030
 
PDF
Concurreny programming
Jaejin Yun
 
PPTX
4장 테스트 자동화의 철학
samagu0030
 
PPTX
Clojure 스터디 Luminus Routing
Cheolhee Han
 
PPTX
20130622 okfn hackathon t2
Seonho Kim
 
PPT
자바와 사용하기2
destinycs
 
PPTX
픽킹
samagu0030
 
PPTX
On lisp ch09
EunPyoung Kim
 
PPTX
On lisp ch18
EunPyoung Kim
 
PPTX
(Lisp)
EunPyoung Kim
 
PDF
데이터베이스 시스템 chapter4_STG박하은
ETRIBE_STG
 
PPTX
Luminus : Html templating
Cheolhee Han
 
PPTX
Refactoring -chapter 7,8-
Kwang Jung Kim
 
PDF
ALLDATA 2015 - RDF Based Linked Data Management as a DaaS Platform
Seonho Kim
 
클로저 1
samagu0030
 
7.데이터수정
Kwang Jung Kim
 
6.테이블만들기
Kwang Jung Kim
 
자연스러운 세부 수준 변화
samagu0030
 
실무로 배우는 시스템 성능 최적화 10부. 네트워크 모니터링
Hyunsoo Jung
 
픽킹
samagu0030
 
Concurreny programming
Jaejin Yun
 
4장 테스트 자동화의 철학
samagu0030
 
Clojure 스터디 Luminus Routing
Cheolhee Han
 
20130622 okfn hackathon t2
Seonho Kim
 
자바와 사용하기2
destinycs
 
픽킹
samagu0030
 
On lisp ch09
EunPyoung Kim
 
On lisp ch18
EunPyoung Kim
 
데이터베이스 시스템 chapter4_STG박하은
ETRIBE_STG
 
Luminus : Html templating
Cheolhee Han
 
Refactoring -chapter 7,8-
Kwang Jung Kim
 
ALLDATA 2015 - RDF Based Linked Data Management as a DaaS Platform
Seonho Kim
 
Ad

Similar to Scala (20)

PDF
Scala, Scalability
Dongwook Lee
 
PDF
Scalability
Dongwook Lee
 
PDF
스칼라와 스파크 영혼의 듀오
Taeoh Kim
 
PPTX
자바프로그래머를 위한 스칼라
Jong Gook Bae
 
PPTX
함수형 사고 - Functional thinking
재문 심
 
PPTX
Feel functional
WonJun Lee
 
PPTX
SLiPP 서비스를 Java에서 Scala로 전환하면서 경험담
Javajigi Jaesung
 
PDF
일단 시작하는 코틀린
Park JoongSoo
 
PDF
Java advancd ed10
hungrok
 
PDF
[D2 campus seminar]스칼라를 통한 다양한 언어의 패러다임 맛보기
NAVER D2
 
PDF
실용주의 디자인패턴 2 인터페이스로 프로그래밍하기
Cosmos Shin
 
PDF
Functional progrmming with scala
오석 한
 
PPTX
Scala, Spring-Boot, JPA의 불편하면서도 즐거운 동거
Javajigi Jaesung
 
PDF
Effective Scala (SpringCamp 2013)
ihji
 
PPTX
[세미나] 20160819 Java 프로그래머를 위한 Scala 튜토리얼
Sanghoon Yoon
 
PDF
Java(1/4)
handfoot
 
PPTX
Java collections framework
경주 전
 
PPTX
Let's Go (golang)
상욱 송
 
PDF
7가지 동시성 모델 4장
HyeonSeok Choi
 
PPTX
객체지향 프로그래밍 기본
용호 최
 
Scala, Scalability
Dongwook Lee
 
Scalability
Dongwook Lee
 
스칼라와 스파크 영혼의 듀오
Taeoh Kim
 
자바프로그래머를 위한 스칼라
Jong Gook Bae
 
함수형 사고 - Functional thinking
재문 심
 
Feel functional
WonJun Lee
 
SLiPP 서비스를 Java에서 Scala로 전환하면서 경험담
Javajigi Jaesung
 
일단 시작하는 코틀린
Park JoongSoo
 
Java advancd ed10
hungrok
 
[D2 campus seminar]스칼라를 통한 다양한 언어의 패러다임 맛보기
NAVER D2
 
실용주의 디자인패턴 2 인터페이스로 프로그래밍하기
Cosmos Shin
 
Functional progrmming with scala
오석 한
 
Scala, Spring-Boot, JPA의 불편하면서도 즐거운 동거
Javajigi Jaesung
 
Effective Scala (SpringCamp 2013)
ihji
 
[세미나] 20160819 Java 프로그래머를 위한 Scala 튜토리얼
Sanghoon Yoon
 
Java(1/4)
handfoot
 
Java collections framework
경주 전
 
Let's Go (golang)
상욱 송
 
7가지 동시성 모델 4장
HyeonSeok Choi
 
객체지향 프로그래밍 기본
용호 최
 
Ad

Scala

  • 1. Why Scala? JBoss Users Club 윤재진
  • 3. CPU의 변화 CPU 속도의 증가는 느려짐 2001년 IBM에서 PowerPC 4 멀티코어 도입 업체들이 CPU 속도보다 코어수를 늘리기 시작함 2007년경 AMD에서 먼저 쿼드코어 CPU 발매 현재는???
  • 5. 현재는?? 그래픽 카드도 듀얼코어 핸드폰도 듀얼코어 노트북은 쿼드코어 개발자는 어떻게 대처를?? Concurrency Programming
  • 6. cpu 변화에 따른 우리는? multi core로만 성능이 향상되지는 않는다 multi core에 맞게 프로그래밍이 되어야지 성능 이 향상이 될 수 있다. 우리는 이에 맞는 프로그래밍을 해야 한다. 현재는 하지 않아도 앞으로 하게 될지 모른다.
  • 7. Concurrency 다행히도 자바에선 Concurrency가 언어 자체에서 지원 synchronized AtomicInteger 등 자바자체적으로 지원 기능이 많음
  • 8. Thread t1 = new Thread (new Runnable() { public void run() { while(true) { System.out.println("tic"); }} }); Thread t2 = new Thread (new Runnable() { public void run() { while(true) { System.out.println("toc"); }} }); ! t1.start(); t2.start(); ! Listing 1: Parallel Threads in Java Thread t1 = new Thread (new Runnable() { public void run() { while(true) { System.out.println("tic"); }} }); Thread t2 = new Thread (new Runnable() { public void run() { while(true) { System.out.println("toc"); }} }); ! t1.start(); t2.start(); ! Listing 2: Pooled Parallel Threading in Java
  • 9. import java.util.concurrent.atomic.AtomicInteger; ! public class AtomicCounter { AtomicInteger ctr = new AtomicInteger(0); public void Increment(int k) { ctr.addAndGet(k); } public void Decrement(int k) { ctr.addAndGet(-k); } } Listing 4: Atomic Increment public class Counter { private int ctr = 0; public synchronized void Increment(int k) { ctr += k; } public synchronized void Decrement(int k) { ctr -= k; } } Listing 3:Synchronized Updates
  • 10. 하지만??? 기본적으로 고려해야할 점은??? Shared Memory 잘못하게 되면?? Dead lock 조금만 더 쉽게 개발은 할 수 없는걸까???? Shared Memory 사용하지 않고 개발
  • 11. Shared Memory 사용않고 개발은? Functional language 사용 erlang : Actor erjang : jvm 위에서 사용하는 erlang clojure : jvm, .net에서 돌아가는 lisp scala : scalable 라고 jvm,.net에 돌아 감
  • 12. Reason 2 지식 자산을 얻는 최선의 길은 무엇일까?
  • 13. 지식 자산을 얻는 최선의 길은 무엇일까? 매년 새로운 언어을 최소 하나는 배워라 기술서적을 분기마다 한권씩 읽어라 비기술 서적도 읽어라 수업을 들어라 지역 사용자 모임에 참여라하 다른환경에서 사용하라 요즘 흐름을 놓치리 마라 인터넷을 이용하라
  • 14. Reason 3 “If I were to pick a language to use today other than Java, it would be Scala” James Gosling
  • 16. Scalable Language ! Grow the Library not the Syntax
  • 17. Scalable Language 에릭 레이몬드가 이야기 했던 성장과 시장 모델에서 시장 모델을 추구함 이미 만들어진 라이브러말고 사용자가 쓰면서 필요한 부분을 오픈소스로 계속 추가하도록 하는게 목적 그래서 Scalable Language라 함
  • 19. ㅋ! Martin Odersky Since 2003 Sponsored by EPFL Pragmatic Runs on the JVM Statically typed Growing new types Seamless integration with Java
  • 20. Concise // Java public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } public void setName(String name) { this.name = name; }} // Scala class Person( var name: String, var age: Int)
  • 21. Pure OO 1 + 2 1.+(2) 123.toString() 모든것들은 객체
  • 22. Pragmatic val joe = <employee name="Joe" rank="code monkey" serial="123" /> XML 선언 scala> joe "@name" res15: scala.xml.NodeSeq = Joe ! scala> joe "@serial" res16: scala.xml.NodeSeq = 123 추출
  • 23. Scala high level // this is Java boolean nameHasUpperCase = false; for (int i = 0; i < name.length(); ++i) { if (Character.isUpperCase(name.charAt(i))) { nameHasUpperCase = true; break; } } val nameHasUpperCase = name.exists(_.isUpper)
  • 24. Scala’s root 많은 언어들에서 영향을 받음 문법은 기본적으로 Java, C#을 채용함 Convention은 C,C++에 빌려옴 Object models 기본적으로 Smalltalk, 부분 적으로 Ruby Actor models은 erlang
  • 26. 변수 선언 val msg = “Hello, World!” var msg2 = “Hello, World!” val : FP 형태의 immutable 선언방식 var : Java 형태의 mutable 선언방식
  • 27. 함수 선언 def max(x: Int, y: Int): Int = { if (x > y) x else y } def max2(x: Int, y: Int) = if (x > y) x else y
  • 28. class class Person( var name: String, var age: Int) class ChecksumAccumulator { // class definition goes here } class Person( var name: String, var age: Int) { var name:String = name; var age: Int = age; } val person = new Person(“jaejin”,30) val checksum = new ChecksumAccumulator
  • 29. object 싱글톤 클래스 scala에서는 static type이 없어서 object을 이용하거나 import로 static을 대신할 수 있다. 사용방법은 똑같은 이름의 class가 같은 scala 파일에 있어야 한다. class와 똑같은 명칭의 object을 선언하면 사용 할 수 있다.
  • 30. object object SingleObject { def printSingle(a:String) { print(a) } } scala> val t = SingleObject scala> t.print(“test”) test scala> SingleObject.print(“test”)
  • 31. Companion object // In file ChecksumAccumulator.scala! class ChecksumAccumulator { ! private var sum = 0 ! def add(b: Byte) { sum += b } ! def checksum(): Int = ~(sum & 0xFF) + 1! }
  • 32. // In file ChecksumAccumulator.scala import scala.collection.mutable.Map object ChecksumAccumulator { private val cache = Map[String, Int]() def calculate(s: String): Int = if (cache.contains(s)) cache(s) else { val acc = new ChecksumAccumulator for (c <- s) acc.add(c.toByte) val cs = acc.checksum() cache += (s -> cs) cs } }
  • 33. expression var filename = "default.txt" ! if (!args.isEmpty)! filename = args(0) val filename = ! if (!args.isEmpty) args(0) ! else "default.txt" for (i <- 1 to 4) ! println("Iteration "+ i) val filesHere = (new java.io.File(".")).listFiles ! for (file <- filesHere if file.getName.endsWith(".scala"))! println(file)
  • 34. trait Rich interface 멤버선언이 가능 abstract 메소드 선언 가능 메소드 구현 가능
  • 35. trait Dad { private var children: List[Child] = Nil ! def addChild(child: Child) = children = child :: children ! def getChildren = children.clone } trait
  • 36. class Man(val name: String) extends Human class Child(val name: String) extends Human Base class Human
  • 37. Static mixin composition class Man(val name: String) extends Human with Dad uasage val sanghun = new Man(“상훈”) sanghun.addChild(new Child(“원희”))
  • 38. Dynamic mixin composition class Man(val name: String) extends Human uasage val sanghun = new Man(“상훈”) with Dad sanghun.addChild(new Child(“원희”))
  • 39. Stackable modifications trait IgnoreCaseSet extends java.util.Set[String] { ! abstract override def add(e: String) = { super.add(e.toLowerCase) } abstract override def contains(e: String) = { super.contains(e.toLowerCase) } abstract override def remove(e: String) = { super.remove(e.toLowerCase) } }
  • 40. Stackable modifications val set = new java.util.HashSet[String] with IgnoreCaseSet set.add(“HI THERE“) // uppercase set.contains(“hi there“) // lowercase => true
  • 41. Stackable modifications trait LoggableSet extends java.util.Set[String] { ! abstract override def add(e: String) = { println(“Add :“ + e) super.add(e) } abstract override def remove(e: String) = { println(“Remove :“ + e) super.remove(e) } }
  • 42. Stackable modifications val set = new java.util.HashSet[String] with IgnoreCaseSet with LoggableSet set.add(“HI THERE“) => “Add: HI THERE”
  • 43. Stackable modifications val set = new java.util.HashSet[String] with LoggableSet with IgnoreCaseSet set.add(“HI THERE“) => “Add: hi there”
  • 44. package, import static import 제공 import java.lang._ import java.lang.Integer._ package 안에 패키지 가능 접근자 없으면 public protected는 사용만 가능하고 패키지에서 접근 불가능
  • 46. first-class def square(x: Int): Int = x * x def sumInts(a: Int, b: Int): Int = if (a > b) 0 else a + sumInts(a + 1, b)
  • 47. FP val inc = (x: Int) => x + 1 scala> inc(1) 2
  • 48. FP - higher order List(1, 2, 3).map((x: Int) => x + 1) List(2,3,4)
  • 49. currying def sum(f: Int => Int): (Int, Int) => Int = { ! def sumF(a: Int, b: Int): Int =! if (a > b) 0 else f(a) + sumF(a + 1, b) ! sumF! } scala> sum(x=>x*x)(1,10) result : Int = 385
  • 50. currying-tail def sum(f: Int => Int)(a: Int, b: Int): Int = { ! def iter(a: Int, result: Int): Int = {! if (a>b) result else iter(a+1, f(a)+result)! iter(a, 0)! } scala> sum(x=>x*x)(1,10) result : Int = 385
  • 51. List 만들기 val list = List(1,2,3) val list2= 1 :: 2 :: 3 :: Nil val list3 = List(1) ::: List(2) ::: List(3) val list4 = 1 :: (2 :: (3 :: Nil)) list == list2 ==list3 == list4 => true
  • 52. List 이해 val list = List(1,2,3) list.head == 1 => true list.tail == List(2,3) => true val head :: tail = List(1,2,3) head == 1 => true tail == List(2,3) => true
  • 53. List 이해 val list = List(1, 2, 3) list.map(_ + 1) list.filter(_ < 2) list.exists(_ == 3) list.drop(2) list.reverse list.sort(_ > _) List.flatten(list) list.slice(2, 3) ... => List(2,3,4) => List(1) true => List(1,3) => List(3,2,1) => List(3,2,1) => List(1,2,3) => List(3)
  • 54. pattern matching def matchAny(a: Any): Any = a match { case 1 => “one” case “two” => 2 case i: Int => “scala.int” case <tag>{ t }</tag> => t case head :: tail => head case _ => default }
  • 55. xml abstract class CCTherm { ! val description: String ! val yearMade: Int ! val dateObtained: String ! val bookPrice: Int!// in US cents ! val purchasePrice: Int // in US cents ! val condition: Int! // 1 to 10! override def toString = description! def toXML = <cctherm>! <description>{description}</description> ! <yearMade>{yearMade}</yearMade> ! <dateObtained>{dateObtained}</dateObtained> ! <bookPrice>{bookPrice}</bookPrice> ! <purchasePrice>{purchasePrice}</purchasePrice> ! <condition>{condition}</condition>! </cctherm>! }
  • 56. xml scala> val therm = new CCTherm { ! val description = "hot dog #5"! val yearMade = 1952 ! val dateObtained = "March 14, 2006" ! val bookPrice = 2199 ! val purchasePrice = 500 ! val condition = 9! }! therm: CCTherm = hot dog #5! scala> therm.toXML! res6: scala.xml.Elem = <cctherm>! <description>hot dog #5</description> ! <yearMade>1952</yearMade> ! <dateObtained>March 14, 2006</dateObtained> ! <bookPrice>2199</bookPrice> ! <purchasePrice>500</purchasePrice> ! <condition>9</condition>! </cctherm>
  • 57. actor val echoActor = actor { ! while (true) { ! receive { ! case msg =>! println("received message: "+ msg)! }! }! }
  • 58. actor scala> echoActor ! "hi there" received message: hi there! scala> echoActor ! 15 received message: 15
  • 59. Q & A
  • 60. 참고자료 http://en.wikipedia.org/wiki/ Functional_programming Programming in scala 2th example in scala http://www.slideshare.net/jboner/pragmatic-real- world-scala-45-min-presentation http://java.sys-con.com/node/419716?page=0,1 http://drdobbs.com/web-development/184405990? pgno=2