Last active
December 28, 2015 08:49
-
-
Save not-for-me/ef3c5c5a76e8633f0bcf to your computer and use it in GitHub Desktop.
Scala의 케이스 클래스 특징~
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 스칼라의 문법인 케이스 클래스와 패턴 매칭 코드로 살펴보기 | |
// regular, non-encapsulated data structures 가 필요할 때 케이스 클래스 사용 | |
// Programming In Scala 15장 예제 코드로 구성 됨 | |
abstract class Expr | |
case class Var(name: String) extends Expr | |
case class Number(num: Double) extends Expr | |
case class UnOp(operator: String, arg: Expr) extends Expr | |
case class BinOp(operator: String, left: Expr, right: Expr) extends Expr | |
// 첫 번째 특징: 기본으로 factory Method 생성해 줌 | |
val v = Var("x") | |
// new가 빠진 factory method는 아래처럼 중첩해서 생성할 때 특히 유용 | |
val op = BinOp("+", Number(1), v) | |
// 두 번째 특징: argument에 대해서 자동으로 public field 선언 해 줌 | |
v.name | |
op.left | |
// 세 번째 특징: toString, hashCode, equals를 기본으로 구현해 줌 | |
println(op) | |
op.right == Var("x") | |
// 네 번째 특징: copy 메서드를 제공한다. 파라미터만 바꿔서 객체 재생성이 용이하다! | |
op.copy(operator = "-") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment