Skip to Content

Interface trong Kotlin

1. Giới thiệu

Interface định nghĩa contract mà class phải implement.

2. Khai báo Interface

interface Drawable { fun draw() } class Circle : Drawable { override fun draw() { println("Drawing circle") } } fun main() { val circle = Circle() circle.draw() }

3. Interface với default implementation

interface Printable { fun print() fun preview() { println("Previewing...") print() } } class Document : Printable { override fun print() { println("Printing document") } // preview() đã có sẵn implementation }

4. Properties trong Interface

interface Named { val name: String // abstract property val greeting: String get() = "Hello, $name" // với default getter } class Person(override val name: String) : Named fun main() { val person = Person("Alice") println(person.greeting) // Hello, Alice }

5. Implement nhiều interfaces

interface Flyable { fun fly() } interface Swimmable { fun swim() } class Duck : Flyable, Swimmable { override fun fly() = println("Flying") override fun swim() = println("Swimming") }

6. Giải quyết conflict

interface A { fun greet() = println("Hello from A") } interface B { fun greet() = println("Hello from B") } class C : A, B { override fun greet() { super<A>.greet() super<B>.greet() } }

7. Interface vs Abstract Class

// Interface - không có state interface Movable { fun move() val speed: Int // abstract } // Abstract class - có thể có state abstract class Vehicle(val brand: String) { abstract fun start() fun honk() { println("Beep!") } }

8. Functional Interface (SAM)

fun interface Clickable { fun onClick() } fun main() { // Lambda expression val button = Clickable { println("Clicked!") } button.onClick() }

9. Interface với Generics

interface Repository<T> { fun findById(id: Int): T? fun findAll(): List<T> fun save(item: T) fun delete(id: Int) } class UserRepository : Repository<User> { private val users = mutableListOf<User>() override fun findById(id: Int) = users.find { it.id == id } override fun findAll() = users.toList() override fun save(item: User) { users.add(item) } override fun delete(id: Int) { users.removeIf { it.id == id } } }

10. Delegation với by

interface Printer { fun print(message: String) } class ConsolePrinter : Printer { override fun print(message: String) = println(message) } class Document(printer: Printer) : Printer by printer { // print() được delegate cho printer } fun main() { val doc = Document(ConsolePrinter()) doc.print("Hello!") // Hello! }

📝 Tóm tắt

  • interface định nghĩa contract
  • Có thể có default implementation
  • Properties abstract hoặc có default getter
  • fun interface cho SAM (Single Abstract Method)
  • by cho delegation
  • Một class có thể implement nhiều interfaces
Last updated on