코틀린(Kotlin) 정적(Static) 변수 개념 정리 포스트입니다. 코틀린은 자바(Java)와 많이 비교되어 안드로이드에서 주 언어로 채택된 언어입니다. Java와 100% 호환이 되는 언어이지만, 다소 상이하게 사용해야 하는 부분들이 있습니다. 그 중 하나인 Static 개념에 대해 다뤄보고자 합니다.
코틀린에서는 static이라는 용어를 사용하지 않습니다. 기본적으로 사용하는 방법은 아래와 같습니다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
위와 같이 ‘const val‘ 를 사용하여 기존 자바와 비교하자면 ‘public static final’와 같이 사용이 가능합니다.
위 방법 외에도 다른 방식의 처리 방법이 있는데, object 지시자를 사용하는 것입니다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object 지시자를 활용하여 ‘class 이름’ 대신 ‘object 이름’을 사용하여 ‘static class’로 선언해주는 것입니다. 이 방법을 사용하면 비교적 Java와 비슷한 모양으로 코드를 구현할 수 있습니다.
또한 object 지시자는 클래스 내부에서도 활용이 가능한데, 아래와 같이 사용이 가능합니다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
‘companion object’를 활용하게되면, 한번에 다양한 변수에 대해서 전역처리를 할 수 있습니다.
하지만, const 선언은 String 타입과 원시(Primitive) 타입에서만 사용이 가능한데요. 그 외의 타입에 대해서도 정적 선언을 해줘야 한다면 아래와 같이 ‘@JvmField’ 처리를 해줘야 합니다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
‘const‘를 ‘@JvmField‘로 대체하면 다양한 타입에 대해서도 처리가 가능해집니다.
위의 방법을 활용하면 대부분의 상황에서 처리가 가능할 것으로 예상됩니다. 저의 경우는 전역처리를 해야하는 변수들을 한 클래스에 모아 ‘companion object‘를 활용합니다. 메모리와 같은 성능 분석은 해보지 않았지만, 당장의 관리측면에서는 매우 깔끔하게 할 수 있기 때문입니다.
지금까지 코틀린(Kotlin) 정적(Static) 변수 개념 정리 포스트였습니다. 다른 코틀린과 관련된 글을 보고 싶으시다면 여기를 눌러주시기 바랍니다.