Scala
스칼라 강좌 (24) - 언더스코어 _
[하마] 이승현 (wowlsh93@gmail.com)
2016. 10. 3. 17:18
언더스코어 _ 는 스칼라에서 어떻게 사용되나?
1. Import
import scala.concurrent._
import 에서 _ 는 모든을 뜻한다. 자바에서 *
2. 디폴트 초기화
class Foo {
var i : Int = _ // i = 0
var s: String = _ // s = null
}
Int 는 0 으로 초기화 되고 String 을 대입하면 null 로 초기화 됩니다.
3. 고계 함수에서 익명 파라미터
( 1 to 10) map { _ + 1 }
4. 부분 함수에서 익명 파라미터
좀 더 정확히 얘기하면 partially applied function. partial function 과 구분된다. 바로가기
def f(i : Int) : String = i.toString
def g = (x: Int) => f(x)
def g2 = f _
def u(i: Int) (d: Double) : String = i.toString + d.toString
def w = u(4) _ // (y: Double) => u(4)(y) 와 동일
println(w(5)) // 45.0 출력
5. 패턴 매칭
expr match {
case List(1,_,_) => "첫번째 요소는 1 이며 3개의 요소를 가진 리스트"
case List(_*) => "0 개나 혹은 더 많은 요소를 가진 리스트"
case Map[_,_] => "아무 타입의 키와 아무 타입의 값을 갖는 맵"
case _ => "나머지 아무거나"
}
6. 제네릭에서 와일드카드
def size(objs: List[_]) : Int = {
objs.size
}
def loggedIn(req: RequestWithAttributes[_]): User = {
...
}
7. 프로퍼티에서 세터
class Test {
private var a = 0
def age = a
def age_=(n:Int) = {
require(n>0)
a = n
}
}
val t = new Test
t.age = 5
println(t.age)
참고 :
http://ananthakumaran.in/2010/03/29/scala-underscore-magic.html
http://www.slideshare.net/normation/scala-dreaded