Kotlin(코틀린)은 JetBrains에서 제작된 프로그래밍 언어로서 구글에서 Android 기본 언어로 채택 되면서 주목받는 hot한 언어가 되었다.

JetBrains의 연구소가 있는 러시아 상트페테르부르크에 있는 코틀린 섬에서 이름을 따왔다고 한다...

 

본 포스팅에서는 Kotlin에서 Class를 만들고 상속받고 사용하는 방법에 대해서 기술하도록 한다.

 

먼저 가장 간단하게 Class 만들기

class Animal

중괄호도 필요 없다. 내용은 비었지만-_- 어쨌건 class 는 class다.

 

그렇다면 Class 사용하는 방법은?

val myAnimal = Animal()

new가 필요 없는 것에 주목.. Kotlin은 class 생성시 new 키워드를 사용하지 않는다.

 

내용이 비었으니 이제 내용을 채워보자. 

Class는 Class 이름, Attribute(member 변수, Property)와 Operation(method)로 구성된다.

 

먼저 Property를 추가...(Kotlin에서는 Attribute를 Property라고 부른다)

다리갯수(nLeg)와 색깔(color)를 추가하며, type 은 nLeg는 Int, color는 String으로 선언한다.

class Animal {
    val nLeg:Int = 4
    val color:String = "yellow"
}

 

Kotlin에서는 class에 기본 getter/setter를 만들어줄 필요가 없다.

val myAnimal = Animal()

println("Number of Leg is ${myAnimal.nLeg}")
println("Color is ${myAnimal.color}")

실행결과는?

Number of Leg is 4
Color is yellow

 

 

IntelliJ에서 Kotlin으로 개발을 하게 되면 Decompiler라는 기능을 통해서 Java로 변경된 code를 확인할 수 있는데, Class에 member만 추가하고 getter/setter가 없어도, Decompiler상에서는 getter/setter가 생성이 된다. 단, val로 선언된 변수의 경우 getter만 생성된다..

Decompiler를 실행하는 방법은 아래 포스팅 참조...

IntelliJ에서 Decompiler를 이용하여 Kotlin을 Java code로 확인하기

 

 

public final class Animal {
   private final int nLeg = 4;
   @NotNull
   private final String color = "yellow";

   public final int getNLeg() {
      return this.nLeg;
   }

   @NotNull
   public final String getColor() {
      return this.color;
   }
}

Property가 변경가능 한 값이면 val 대신 var로 선언해주면 된다.

class Animal() {
    val nLeg:Int = 4
    val color:String = "yellow"
    var name:String = "Tom"
}

 

&아래와 같이 {class 변수 이름}.{property 이름} 으로 접근하고 수정 가능

val myAnimal = Animal()

println("Name of the Animal is ${myAnimal.name}")
myAnimal.name = "Smith"
println("Name of the Animal is ${myAnimal.name}")

실행결과

Name of the Animal is Tom
Name of the Animal is Smith

 

 

 

이번에는 method를 추가해 보자

Anmial Class에 eat()와 cry() method를 추가 한다.

class Animal() {
    val nLeg:Int = 4
    val color:String = "yellow"
    var name:String = "Tom"

    fun eat(something:String) {
        println("Eat $something")
    }

    fun cry() {
        println("Cry!!!")
    }
}

확인해보면...

val myAnimal = Animal()

myAnimal.cry()
myAnimal.eat("apple")
Cry!!!
Eat apple

 

 

본 포스팅의 소스는 아래 github에서 확인 가능하다

https://github.com/jeng832/blog-example/tree/master/21_Kotlin%EC%97%90%EC%84%9C%20Class%20%EC%84%A0%EC%96%B8%ED%95%98%EA%B8%B0

+ Recent posts