[code]
fun main() {
EventPrinter().start()
}
interface EventListener {
fun onEvent(count: Int)
}
class EventPrinter: EventListener {
override fun onEvent(count: Int) {
print(“${count}-“)
}
fun start() {
val counter = Counter(this)
counter.count()
}
}
class Counter(var listener: EventListener) {
fun count() {
for (i in 1..100) {
if (i % 5 == 0) listener.onEvent(i)
}
}
}
[/code]
EventPrinter 를 익명객체로 구현할 수도 있다.
[code]
class EventPrinter {
fun start() {
val counter = Counter(object: EventListener {
override fun onEvent(count: Int) {
print(“${count}-“)
}
})
counter.count()
}
}
[/code]
출력결과
[code]
5-10-15-20-25-30-35-40-45-50-55-60-65-70-75-80-85-90-95-100-
[/code]