Clean Code that Works.

Java 8 부터 interface에도 body를 가진 Default Methods 를 지원.

 

import java.time.*; 
 
public interface TimeClient {
    void setTime(int hour, int minute, int second);
    void setDate(int day, int month, int year);
    void setDateAndTime(int day, int month, int year,
                               int hour, int minute, int second);
    LocalDateTime getLocalDateTime();
    default ZonedDateTime getZonedDateTime(String zoneString) {
        return ZonedDateTime.of(getLocalDateTime(), getZoneId(zoneString));
    }
}

위 getZonedDateTime 처럼 interface를 구현한 클래스들에서 쉽게 사용할 수 있는 유틸성 메소드다.

그 전에는 이런 유틸성 메서드들은 따로 유틸리티 클래스를 만들어서 쓰던가, 인터페이스를 구현한 추상 클래스에 넣어서 쓰던지 하는 방법을 써야됬다.

 

아무는 Default Method 쓰면 좀 편해지는 부분이 있다.

 

하지만 Kotlin 에서 Default Method를 지원하지 않는다. 

@JvmDefault 라는 Annotation 을 통해 지원하긴 한데, 컴파일 옵션 추가가 필요하고, 아직 실험적인 단계의 메서드다.

기존 코드를 변경하는 경우에는 @JvmDefault 를 사용하고 하거나 companion object 로 사용하는 방법이 있다.

interface TimeClient {
	fun setTime(hour: Int, minute: Int, second: Int)

	companion object {

		fun getZonedDateTime(zoneString: String): ZonedDateTime {
			return ZonedDateTime.of(LocalDateTime.now(), ZoneId.of(zoneString));
		}
	}
}

 

아에 Kotlin 으로 작업할 경우에는 Default Method와 비슷하게 funtion body 를 작성해주면 된다.

 

interface TimeClient {
	fun setTime(hour: Int, minute: Int, second: Int)
	
	fun getZonedDateTime(zoneString: String): ZonedDateTime {
		return ZonedDateTime.of(LocalDateTime.now(), ZoneId.of(zoneString));
	}
}

class TimeChecker: TimeClient {
	override fun setTime(hour: Int, minute: Int, second: Int) {
		TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
	}

}

공식 문서가 굉장히 잘 되어 있다.

스프링 문서도 잘 되있음!

 

공식 문서 : https://kotlinlang.org/docs/reference/

 

Reference - Kotlin Programming Language

 

kotlinlang.org

Spring Kotlin 문서 : https://docs.spring.io/spring/docs/current/spring-framework-reference/languages.html#kotlin-resources

 

Language Support

Spring provides comprehensive support for using classes and objects that have been defined by using a dynamic language (such as Groovy) with Spring. This support lets you write any number of classes in a supported dynamic language and have the Spring conta

docs.spring.io

Lombok 사용 중 일경우 참고 : https://dzone.com/articles/migrating-from-lombok-to-kotlin

Lombok 으로 작성된 코드를 Kotlin 코드에서 접근할 수 없다. 

Lombok은 컴파일 시 Annotation Processor 에 의해 동작하는데 Kotlin 컴파일시 Annotaion Processor 를 사용하지 않는다.

 

 

Migrating From Lombok to Kotlin - DZone Java

There are a lot of benefits to migrating from Lombok to Kotlin, including reduced verbosity, shorter code, and improved readability.

dzone.com

Spring one 에서 발표된 Kotlin 관련 영상 : https://www.youtube.com/results?search_query=spring+one+kotlin

 

spring one kotlin - YouTube

 

www.youtube.com