Sobes.tech
Junior

Ako sa realizuje implementácia rozhraní v Kotlin?

sobes.tech AI

Odpoveď od AI

Rozhrania v Kotlin sa implementujú pomocou kľúčového slova implements (nejasné v Kotlin, jednoducho sa uvádza dvojbodkou) alebo by na delegovanie.

Hlavné spôsoby implementácie:

  1. Priama implementácia: Objekt alebo trieda implementuje všetky členy rozhrania priamo.
    interface MyInterface {
        fun doSomething()
        val myProperty: String
    }
    
    class MyClass : MyInterface {
        override fun doSomething() {
            println("Doing something in MyClass")
        }
    
        override val myProperty: String = "Hello"
    }
    
    Pri dedení od triedy a implementácii rozhraní naraz, trieda sa uvádza prvá.
    open class BaseClass
    
    class AnotherClass : BaseClass(), MyInterface {
        override fun doSomething() {
            println("Doing something in AnotherClass")
        }
    
        override val myProperty: String = "World"
    }
    
  2. Delegovanie implementácie: Implementácia rozhrania sa deleguje na iný objekt. Používa sa kľúčové slovo by. Toto je užitočné pre kompozíciu a vyhýbanie sa problémom s viacerým dedičstvom implementácie.
    interface DelegatedInterface {
        fun performAction()
    }
    
    class DelegatedObject : DelegatedInterface {
        override fun performAction() {
            println("Action performed by DelegatedObject")
        }
    }
    
    class ImplementingClass(di: DelegatedInterface) : DelegatedInterface by di {
        // ImplementingClass deleguje implementáciu metódy performAction() na objekt di
    }
    
    V tomto prípade ImplementingClass neimplementuje performAction sám, namiesto toho volanie performingClass.performAction() je presmerované na di.performAction().

Pri implementácii viacerých rozhraní s rovnakými členmi je potrebné vyriešiť konflikty, jasne prepísaním člena a uvedením, z ktorého rozhrania sa berie implementácia, pomocou syntaxe <Rozhranie>.<člen>.

interface InterfaceA {
    fun foo() { println("InterfaceA") }
    fun bar()
}

interface InterfaceB {
    fun foo() { println("InterfaceB") }
    fun bar() { println("InterfaceB bar") }
}

class ResolvingConflict : InterfaceA, InterfaceB {
    override fun foo() {
        super<InterfaceA>.foo() // Voláme implementáciu foo z InterfaceA
        super<InterfaceB>.foo() // Voláme implementáciu foo z InterfaceB
    }

    override fun bar() {
        super<InterfaceB>.bar() // Používame implementáciu bar z InterfaceB
    }
}