본문 바로가기

1.1 주생성자 부생성자 본문

Kotlin + SpringBoot

1.1 주생성자 부생성자

00rigin 2023. 10. 1. 18:03

Java와 Kotlin은 유사한듯 다른 생성자 형태를 가지고 있다.

이번에 작성한 Entity를 살펴보자.

@Entity
@Getter
class Memo(title: String,
           description: String) : BaseEntity(){

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private val id: Long? = null

    @Column(nullable = false)
    private var title: String = title

    @Column(nullable = false)
    private var description: String = description

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "parent_id")
    private var parent: Memo? = null
    
    
    constructor (title: String, description: String, parent: Memo) : this(title, description) {
        this.parent = parent
    }
}

Kotlin은 암시적으로 주생성자를 제공한다.

클래스 선언시 소괄호 안에 파라미터를 받아 주 생성자를 호출하는 형식이다.

 

만약 파라미터 갯수가 다르거나, 주 생성자와 다른 형식의 생성자가 필요하다면 부 생성자를 정의 해야 한다.

Kotlin 클래스에서 생성자는 constructor 라는 function을 통해 정의한다.

이 경우, 부 생성자는 주 생성자를 상속받아 만들 수 있다.

Comments