DEV Community

sunj
sunj

Posted on

Kotlin companion, 2024-03-18

class Book private constuctor(val id: Int, val name : String){
   companion object BookFactory : IdProvider{
      override fun getId() : Int {
          return 202
      }
      val myBook = "new book"
      fun create()= Book(getId(), myBook)
   }
}

interface IdProvider {
   fun getId() : Int
}

fun main(){
   val book = Book.create()
   val bookId = Book.BookFactory.getId()
   println("${book.id} ${book.name}")
}
Enter fullscreen mode Exit fullscreen mode

companion 오브젝트는 private 메소드나 프로퍼티를 읽어올 수 있는 기능을 함. 자바의 static의 역할

참조 : Code with Joyce

Top comments (0)