6장 functional objects - codeport/scala GitHub Wiki


kingori

###6.1

Rational에 대한 일반적인 소개. skip해도 무방

###6.2

class 선언 시 클래스명 뒤에 () 로 class parameter를 명시할 수 있음. 이 parameter를 받는 생성자가 primary constructor임. class 내부의 코드 중 field나 method 선언에 해당하지 않는 모든 코드는 primary constructor에 속함.

###6.3

별 내용 없음

###6.4

require 메서드를 이용하면 조건 판단을 할 수 있음. (assert문이랑 비슷한 용도?) IllegalArgumentExceeption을 던짐.

###6.5

필드를 선언하려면 val, var 로 명시해야 함. 10.6절에 소개될 parametric fields를 이용하면 귀찮게 생성자와 별도로 val/var를 선언할 필요 없음. class Rational(n: Int, d: Int) -> class Rational(val n: Int, val d: Int)

###6.6

this로 자기 자신을 참조할 수 있음.

###6.7

  • primary constructor 이외의 다른 생성자를 auxiliary constructor라고 함. 이 aux constructor 내부의 코드는 this(...) 형태의 다른 aux constructor나 primary constructor 호출로 시작되어야 함. 결국엔 primary constructor가 실행되어야 함.

혹시나 primary constructor를 호출하지 않는 경우가 있을까 해서 잠깐 실험을 해 보니 compile 오류가 발생함.

class A( a: Int ) {
    def this( a: Double) = this(a,1)
    def this( a: Double, n: Int ) = this(a)
}

<console>:6: error: called constructor's definition must precede calling constructor's definition
    def this(n: Double) = this(n,1)

즉, 생성자가 호출할 다른 생성자는 자신보다 코드 상에서 앞에 선언되어야 함. 이를 보면 반드시 primary constructor가 실행되리라고 유출할 수 있음.

  • primary constructor만 super class의 constructor를 호출할 수 있음

###6.8 , 6.9

skip

###6.10

  • scala의 identifier는 alphanumeric과 operator로 나뉨
  • alphanumeric identifier : letter, underscore로 시작함. $도 사용 가능하지만, scala 내부 구현과 혼동을 일으키기 때문에 쓰면 안됨! ** naming convention은 자바와 동일(camel case). 단, 상수 정의 시 자바에선 X_OFFESET과 같이 표현했으나 scala는 XOffset과 같이 상수에도 camel case를 사용함.
  • operator identifier: 하나 이상의 opertaor 문자(+, :, ?, ~, #)로 구성됨.
  • mixed identifier: alphanumeric identifier + _ + operator identifier. ex. unary_+, myvar_= (요 형태는 18장의 properties에서 응용한다고 함)
  • literal identifier: back tick 사이에 표기한 string. ex. x, yeild. java에서 scala reserved word등을 사용할 때.

###6.11

skip

###6.12

skip

###6.13

implicit conversion, operator 재정의는 코드를 간결하게 하는 데 유용하긴 하지만, 남들이 코드를 읽을 때 혼동의 여지를 주기도 하므로 주의해서 사용해야 함.

Outsider

6.1 A specification for class Rational

6.2 Constructing a Rational

  • 클래스명 뒤에 괄호 안에오는 파라미터를 클래스 파라미터라고 부고 primary 생성자에 전달한다.
  • 불면객체
    • 장점
      • 뮤터블 보다 쉽다.
      • 걱정없이 전달할 수 있다.
      • 동시성에 대한 걱정이 없다.
      • 안전한 해쉬테이블 키를 만들 수 있다.
    • 단점
      • 큰 객체를 복사할때 비용이 든다.
  • 필드나 메서드 정의가 아닌 클래스의 바디에 있는 코드가 primary 생성자가 된다

6.3 Reimplementing the toString method

6.4 Checking preconditions

  • require를 사용해서 메서드나 생성자에 전달된 값을 체크할 수 있다.
  • require는 boolean값을 파라미터로 받는다.
  • require가 충족되지 않으면 IllegalArgumentException 예외가 발생한다.

6.5 Adding fields

6.6 Self references

6.7 Auxiliary constructors

  • primary constructor가 아닌 생성자는 auxiliary constructor라고 부른다.
  • auxiliary 생성자는 primary 생성자를 항상 호출해서 primary 생성자가 엔트리 포인트가 된다.
  • 오직 primary 생성자만 superclass 생성자를 호출할 수 있다.

6.8 Private fields and methods

6.9 Defining operators

6.10 Identifiers in Scala

  • $도 identifier에 사용할 수 있지만 예약어이므로 사용하지 마라
  • 상수는 val과는 다르다. val은 변수다
  • 스칼라의 상수 관례는 첫글자를 대문자로 쓴 캐멀케이스이다.
  • 스칼라에서 기호로된 오퍼레이터는 자바의 identifier로 변환된다. :->는 $colon$minus$greater 가 된다.
  • 리터럴 identifier는 ``로 감쌀 수 있다.

6.11 Method overloading

6.12 Implicit conversions

6.13 A word of caution

질문

  • 불변객체 단점 잘 모르겠음(p141)
⚠️ **GitHub.com Fallback** ⚠️