val/var in Constructor

About

μ½”ν‹€λ¦°μ—λŠ” μ£Όμƒμ„±μž(primary constructor)이라고 ν•˜λŠ”, μƒμ„±μž λ©”μ†Œλ“œ μ„ μ–Έκ³Ό λ™μ‹œμ— ν”„λ‘œνΌν‹°λ₯Ό μΆ”κ°€ν•΄μ£ΌλŠ” νŽΈλ¦¬ν•œ κΈ°λŠ₯이 μžˆλ‹€.

그런데 가끔 클래슀 생성에 ν•„μš”ν•˜μ§€λ§Œ ν”„λ‘œνΌν‹°λ‘œλŠ” λ§Œλ“€κ³  싢지 μ•Šμ€ κ²½μš°κ°€ μžˆλ‹€. 이런 κ²½μš°μ—” μ–΄λ–»κ²Œ ν•΄μ•Όν• κΉŒ?

Solution

정닡은 "val / var을 λΉΌλ©΄ λœλ‹€"이닀.

μ£Όμƒμ„±μžμ— val λ˜λŠ” var을 μΆ”κ°€ν•΄ λ§€κ°œλ³€μˆ˜λ₯Ό λ„£μœΌλ©΄ ν”„λ‘œνΌν‹°λ₯Ό 생성해쀀닀.

λ°˜λŒ€λ‘œ, 적지 μ•ŠλŠ”λ‹€λ©΄ (primary) constructor parameterκ°€ λ˜μ–΄ κ·Έλƒ₯ ν•΄λ‹Ή 이름을 가진 νŒŒλΌλ―Έν„°κ°€ 될 뿐이닀. ν•΄λ‹Ή 값은 init 블둝 λ˜λŠ” λ‹€λ₯Έ ν”„λ‘œνΌν‹°λ₯Ό μ΄ˆκΈ°ν™”ν•˜λŠ” 데 μ‚¬μš©ν•  수 μžˆλ‹€.

class User(
    val id: Long,
    email: String,
) {
    val hasEmail = email.isNotBlank() // email can be accessed here
    init {
        // email can be accessed here
    }
    
    fun getEmail(): String {
        // email can't be accessed here
    }
}

REF

Last updated