Object 용도
Object Expressions
Object Declarations
Companion Object
객체 표현식
btn.setOnClickListner(new OnClickListener() {
public void onClick(View v){
}
});
객체 표현식 문법
window.addMouseListener(object : MouseAdapter() {
override fun mouseClicked(e: MouseEvent) {}
override fun mouseEntered(e: MouseEvent) {}
}
객체 표현식 상속
open class A(x: Int) {
public open val y: Int = x
}
interface B {...}
val ab: A = object : A(1), B {
override val y = 15
}
객체 표현식 상속 없는 경우
val adHoc = object {
var x: Int = 0
var y: Int = 0
}
print(adHoc.x + adHoc.y)
0
객체 표현식 제약 사항
class C {
private fun foo() = object { val x: String = "x"}
fun publicFoo() = object { val x: String = "x"}
fun bar() {
val x1 = foo().x // OK
val x2 = publicFoo().x // error
}
}
객체 표현식 특징
fun countClicks(window: JComponent) {
var clickCount = 0
var enterCount = 0
window.addMouseListener(object : MouseAdapter(){
obrride fun mouseClicked(e: MouseEvent){
clickCount++
}
obrride fun mouseEntered(e: MouseEvent){
enterCount++
}
})
}
객체 선언 용도
object DataProviderManager {
fun registerDataProvider(provider: DataProvider){
// ...
}
val allDataProviders: Collection<DataProvider>
get() = // ...
}