of, from 메서드 차이

DragonTiger·2023년 8월 25일
0

정확한 의미를 모른채 사용하다 보니 궁금해서 of, from 의 차이를 검색 및 정의해본다.

of

of는 같은 타입 또는 유사한 형태의 원시 값들을 받아 객체를 생성할 때 사용되며,
명확한 유효성 검사 또는 단순한 가공 로직이 포함될 수 있다.

companion object {
        fun of(value: String): X {
            return X(value)
    	}
}

from

from은 다른 타입이거나 의미적으로 다른 객체를 입력받아,
그 값을 해석 또는 변환해 새로운 객체를 생성할 때 사용한다.


class X {

  companion object {
          fun from(value: String): Y {
              return Y(value)
          }
  }

}

추가로 간단한 메서드들

of : 값을 받아 객체를 직접 생성 Money.of(1000)
from : 다른 타입의 객체를 해석해서 생성 Duration.from(temporal: TemporalAmount)
valueOf : enum, String → enum 같은 정해진 매핑일 때 Day.valueOf("MONDAY")
parse : 문자열 등 문법적으로 해석할 때 LocalDate.parse("2024-05-29")

profile
take the bull by the horns

0개의 댓글