반응형

1. object

object 키워드는 코틀린에서 클래스를 정의하면서 동시에 객체를 생성하는 키워드 이다

class 자리에 object 키워드를 사용하면 된다

 

1) 객체 선언

  • class 대신 object 키워드를 사용하면 클래스를 선언함과 동시에 객체를 생성하게되고 이는 싱글톤 객체가 된다
object Counter {
	private var count: Int = 0
	
	fun plus() {
		count++
	}
	
	fun getCount() = count
}

fun main() {
	println(Counter.getCount())
	Counter.plus()
	Counter.plus()
	println(Counter.getCount())
}

 

2) 객체 식

  • 익명클래스를 통해 객체를 생성할 때 사용
interface Person {
	fun work()
}

fun main() {
	val worker = object: Person {
		override fun work() {
			println("일한다!")
		}
	}
	
	worker.work()
	
}

 

3) 동반 객체(companion)

  • 클래스의 객체들이 공유해야하는 메소드나 프로퍼티를 정의할 때 사용
  • Factory Method 패턴 사용시 활용 가능
class User private constructor(val id: Int) {
    companion object {
        fun create(id: Int): User {
            return User(id)
        }
    }
}

fun main() {
    val user = User.create(1111)
    println(user.id)  // 1111
}

마치 자바의 static 키워드를 사용하는 것과 비슷한 효과가 나온다(코틀린에는 static이 존재하지 않는다)

컴패니언(companion) 객체는 최종적으로 jvm 바이트코드로 컴파일(.class) 될 때 static 멤버로 컴파일 된다

반응형

+ Recent posts