개발/Kotlin&JAVA
코틀린에서 static class 사용하기 : companion object - 자바와 다른 점 3
애쿠
2024. 2. 1. 17:53

스프링+자바에서는 종종 static 클래스나 매서드를 쓴다.
static 매서드/클래스를 쓰게 되면, 빈보다 먼저 생성되기 때문에 굉장히 유용하게 쓸 수 있는데,
코틀린에서는 특이하게 static이라고 명명하지 않고 다른 이름으로 사용한다.
companion object라는 이름으로 사용하는데 자바에서의 static과는 사용법이 조금 다르다.
공용 클래스에 static 매서드로 만들어진 UTC <-> KST 시간 변환 매서드가 있다고 해보자.
Java
public class CommonUtils {
public static LocalDateTime convertToUtc(LocalDateTime localDateTime) {
if (localDateTime == null) {
return null;
}
ZonedDateTime zonedDateTimeKst = ZonedDateTime.of(localDateTime, ZoneId.of("Asia/Seoul"));
ZonedDateTime zonedDateTimeUtc = zonedDateTimeKst.withZoneSameInstant(ZoneId.of("UTC"));
return zonedDateTimeUtc.toLocalDateTime();
}
public static LocalDateTime convertToKst(LocalDateTime localDateTime) {
if (localDateTime == null) {
return null;
}
ZonedDateTime zonedDateTimeUtc = ZonedDateTime.of(localDateTime, ZoneId.of("UTC"));
ZonedDateTime zonedDateTimeKst = zonedDateTimeUtc.withZoneSameInstant(ZoneId.of("Asia/Seoul"));
return zonedDateTimeKst.toLocalDateTime();
}
}
kotlin
class CommonUtils {
companion object {
fun convertToUtc(localDateTime: LocalDateTime?): LocalDateTime? {
localDateTime ?: return null
val zonedDateTimeKst = ZonedDateTime.of(localDateTime, ZoneId.of("Asia/Seoul"))
val zonedDateTimeUtc = zonedDateTimeKst.withZoneSameInstant(ZoneId.of("UTC"))
return zonedDateTimeUtc.toLocalDateTime()
}
fun convertToKst(localDateTime: LocalDateTime?): LocalDateTime? {
localDateTime ?: return null
val zonedDateTimeUtc = ZonedDateTime.of(localDateTime, ZoneId.of("UTC"))
val zonedDateTimeKst = zonedDateTimeUtc.withZoneSameInstant(ZoneId.of("Asia/Seoul"))
return zonedDateTimeKst.toLocalDateTime()
}
}
}
별도의 scope로 묶어서 관리한다.
클래스의 멤버 매서드와 static 매서드가 혼재되는 걸 막기 위해서 사용되는 것 같다.
특이한 점이 있다면, 확장 함수(Extention) 기능이 있는데 이 companion object의 매서드를 외부에서 추가할 수 있다.
// CommonUtils.Companion의 확장 함수로 다른 시간대로 변경하는 기능을 추가
fun CommonUtils.Companion.convertLocalDateTimeToZone(dateTime: LocalDateTime, zoneId: ZoneId): LocalDateTime {
val zonedDateTime = ZonedDateTime.of(dateTime, ZoneId.systemDefault())
val targetZoned = zonedDateTime.withZoneSameInstant(zoneId)
return targetZoned.toLocalDateTime()
}
val newYorkDateTime = CommonUtils.convertLocalDateTimeToZone(localDateTime, ZoneId.of("America/New_York")) // 뉴욕 시간대로 변환
이게 언제 사용될지는 모르겠는데, 이렇게 분산해서 매서드를 만들어 버리면 오히려 가독성과 사용성을 떨어트리진 않을까? 라는 생각이 든다.