본문 바로가기

프로그래밍/scala

스칼라 함수형 객체

클래스 선언, 메소드 오버라이드, 인스턴스 생성 시 전제조건precondition

import scala.language.implicitConversions // 이 문구를 명시적으로 넣어줘야 아래의 경고 문구가 뜨지 않는다.

// warning: implicit conversion method intToRational should be enabled 


class Rational(n: Int, d: Int) { // constructur


  val g: Int = gcd(n.abs, d.abs)

  val numer: Int = n / g // 넘어온 객체의 필드에 접근하기 위해서는 필드 정의가 반드시 필요

  val denom: Int = d / g


  override def toString = 

    if (d == 1) numer.toString else numer.toString + "/" + denom.toString // 연산자 오버로딩operator overloading


  require (d != 0) // 전제조건precodition

  // require에 만족하지 못 하면 throw java.lang.IllegalArgumentException: requirement failed


  println("분수 인스턴스 생성 : " + this) // 클래스 내에 어떤 위치에서도 출력이 가능함


  def +(that: Rational) : Rational = // 덧셈 연산자 오버로딩operator overloading

    new Rational(

      numer * that.denom + that.numer * denom,

      denom * that.denom

    )


  def +(that: Int) : Rational = 

    new Rational(

      numer + that * denom,

      denom

    )

 

  def *(that: Rational) : Rational = // 곱셈 연산자 오버로딩

    new Rational(

      numer * that.numer,

      denom * that.denom

    ) 

  

  def *(that: Int) : Rational =

    new Rational(

      numer * that,

      denom

    )

  

  def lessThan(that: Rational) : Boolean =

    numer * that.denom < denom * that.numer


  def max(that: Rational) : Rational =

    if (lessThan(that)) that else this // 자기참조self reference

      

  def this(n: Int) = this(n, 1) // 보조 생성자auxiliary constructor

    

  def gcd(a: Int, b: Int) : Int =

    if (b == 0) a else gcd(b, a % b) // 최대공약수 구하는 함수

    

}


현재 실행경로 알아내는 클래스

class Common() {

  def pwd = new java.io.File(".").getCanonicalPath

}


'프로그래밍 > scala' 카테고리의 다른 글

Maven + Java + Spark 연동 개발  (0) 2016.02.04
스칼라의 기본 타입과 연산  (0) 2016.01.16
스칼라의 클래스와 객체  (0) 2016.01.16