Rooted In Develop

Kotlin - 클래스, 객체, 인터페이스 본문

Back End/Kotlin

Kotlin - 클래스, 객체, 인터페이스

RootedIn 2023. 5. 1. 11:13

인터페이스

interface Clickable {
    fun click()
    fun showOff() = println("clickable")
}

interface Focusable {
    fun setFocus(b: Boolean) = println("${if (b) "got" else "lost"} focus")
    fun showOff() = println("focusable")
}

class Button : Clickable, Focusable {
    override fun click() = println("click")
    override fun showOff() {
        super<Clickable>.showOff()
        super<Focusable>.showOff()
    }
}

 

클래스

open class RichButton : Clickable {
    fun disable() {} // final
    open fun animate() {} // open
    override fun click() {} // open(default)
    final override fun click() {} // final
}

abstract class Animated {
    abstract fun animate()
    open fun stopAnimating() {} // open
    fun animateTwice() {} // final
}

- final : override 불가
- open : override 가능
- abstract : override 필수

- public : 모든 곳
- internal : 같은 모듈
- protected : 하위 클래스
- private : 같은 클래스

 

내부 클래스에서 외부 클래스 참조에 접근하려면 this@Outer

class Outer {
    inner class Inner {
        fun getOuterReference(): Outer = this@Outer
    }
}

 

sealed class

interface Expr
class Num(val value: Int) : Expr
class Sum(val left: Expr, val right: Expr) : Expr
fun eval(e: Expr): Int =
    when (e) {
        is Num -> e.value
        is Sum -> eval(e.right) + eval(e.left)
        else -> throw Exception() // else 분기 필수
    }
}

sealed class Expr {
    class Num(val value: Int) : Expr()
    class Sum(val left: Expr, val right: Expr) : Expr()
}
fun eval(e: Expr): Int =
    when (e) {
        is Expr.Num -> e.value
        is Expr.Sum -> eval(e.right) + eval(e.left)
        // else 없어도됌
    }

 

데이터 클래스

- equals, hashCode, toString 메소드 포함

 

'Back End > Kotlin' 카테고리의 다른 글

Kotlin - 연산자 오버로딩  (0) 2023.05.27
Kotlin - 타입 시스템  (0) 2023.05.06
Kotlin - 람다 프로그래밍  (0) 2023.05.01
Kotlin - 함수 정의와 호출  (0) 2023.04.15
Kotlin - 기초  (0) 2023.04.15
Comments