Created
October 5, 2015 06:33
-
-
Save not-for-me/cd8a3f1a9ec18d499459 to your computer and use it in GitHub Desktop.
스칼라의 클래스 선언 샘플
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
package nfm.ex06 | |
/** | |
* Programming In Scala 2/e List 6.5 코드 | |
* 분수 Class | |
* @param n 분자 | |
* @param d 분모 | |
*/ | |
/* 스칼라에 있는 문법: Class에서 기본 생성자 선언 가능 | |
* n과 d는 class parameter 자동 생성 | |
* class parameter에 val 또는 var 선언을 하지 않으면 외부로 노출 되지 않음*/ | |
class Rational(val n: Int, d: Int) { | |
/* 스칼라에 있는 문법: 생성자의 값 Validation */ | |
require(d != 0) | |
/* 자바와 동일: 필드 선언 */ | |
private val g = gcd(n.abs, d.abs) | |
val numerator = n / g | |
val denominator = d / g | |
/* 스칼라는 반드시 기본 생성자를 재활용하여 다양한 생성자 선언 | |
* 따라서 custom 생성자는 반드시 기본 생성자를 호출하게 되어 있음 */ | |
def this(n: Int) = this(n, 1) | |
/* 자바와 동일: 메서드 오버로드 */ | |
def +(that: Rational): Rational = | |
new Rational(numerator * that.denominator + that.numerator + denominator, denominator * that.denominator) | |
def +(i: Int): Rational = | |
new Rational(numerator + i * denominator, denominator) | |
def -(that: Rational): Rational = | |
new Rational(numerator * that.denominator - that.numerator * denominator, denominator * that.denominator) | |
def -(i: Int): Rational = | |
new Rational(numerator - i * denominator, denominator) | |
def *(that: Rational): Rational = | |
new Rational(numerator * that.numerator, denominator * that.denominator) | |
def *(i: Int): Rational = | |
new Rational(numerator * i, denominator) | |
def /(that: Rational): Rational = | |
new Rational(numerator * that.denominator, denominator * that.numerator) | |
def /(i: Int): Rational = | |
new Rational(numerator, denominator * i) | |
/* 자바와 동일: 메서드 오버라이드 */ | |
override def toString = numerator + "/" + denominator | |
/* private 메서드, */ | |
private def gcd(n1: Int, n2: Int): Int = if (n2 == 0) n1 else gcd(n2, n1 % n2) | |
} | |
/* 스칼라는 자바보다 좀 더 객체지향적: class 필드(static field)가 없다. | |
* 대신 정적 필드를 object에 넣고, 한 파일에 동일한 이름의 class와 object가 있을 경우 Companion Object라 함. | |
* 아래는 App을 상속받아 main 진입점을 자동을 삽입하게 한 예 */ | |
object Rational extends App { | |
val test = new Rational(2, 3) | |
println(test.n) | |
println(test * 6) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment