아래의 글은 마틴 오더스키,렉스 스푼,빌 베너스 공저 / 오현석,이동욱,반영록 공역, 『Programming in Scala 3/e』,에이콘출판사(2017), CH01의 내용을 기반으로 작성하였습니다.
바운드 변수 , 자유변수 및 클로저
object FileMatcher {
private def fileHere = (new java.io.File(".")).listFiles private def filesMatching(matcher: String => Boolean) = for (file <- filesHere; if matcher(file.getName)) yield file
def filesEnding(query: String) = filesMatching(_.endsWith(query)) def filesContaining(query: String) = filesMatching(_.contains(query)) def filesRegex(query: String) = filesMatching(_.matches(query)) } |
def containsNeg(nums: List[Int]): Boolean = { var exists = false for (num <= nums) if ( num < 0) exists = true exists }
def containsNeg(nums: List[Int]) = nums.exists(_ < 0) |
curring
def curriedSum(x: Int)(y: Int) = x + y def first (x: Int) = (y: Int) => x + y |
새로운 제어 구조
def twice(op: Double => Double, x : Double) = op(op(x))
twice(_ + 1, 5) 7.0 |
인자 단 하나만을 전달하는 경우 소괄호 대신 중괄호를 사용할 수 있다
def withPrintWriter(file: File)(op: PrintWriter => Unit) = { val writer = new PrintWriter(file) try { op(writer) } finally { writer.close() } }
var file = new File("date.txt")
withPrintWriter(file) { writer => writer.println(new java.util.Date) } |
이름에 의한 호출
var assertionEnabled = true
def myAssert(predicate: () => Boolean) = if (assertionEnabled && !predicate()) throw new AssertionError
myAssert(() => 5 > 3)
def byNameAssert(predicate: => Boolean) = if (assertionEnabled && !predicate()) throw new AssertionError
myNameAsset(5 > 3) -- 5 > 3을 계산하는 내용의 apply 메소드가 드어간 함수 값을 만들어서 byNameAssert 로 넘긴다 -- 안의 계산식을 먼저 계산 안 함.
def boolAssert(predicate: Boolean) = if (assertionEnabled && !predicate()) throw new AssertionError
booleanAssert( 5 > 3) -- 결과를 직접 넘김 -- assertionEnabled = false여도 안의 계산식을 먼저 계산함. -- side effect 가 있을 수 있음
var x = 5
var assertionEnabled = false;
boolAssert(x / 0 == 0)
java.lang.ArithmeticException : / by zero
byNameAssert( x / 0 == 0) -- 에러 없음 |