Junior
Kā tiek īstenotas interfeiss Kotlin?
sobes.tech AI
Atbilde no AI
Kotlin saskarnes tiek realizē ar atslēgas vārdu implements (nav tieši Kotlin, vienkārši norādīts ar divpunkti) vai by deleģēšanai.
Galvenie realizēšanas veidi:
- Tieša realizācija: Objekts vai klase tieši realizē visas saskarnes locekļus.
Mantojot no klases un realizējot saskarnes vienlaikus, klase tiek norādīta pirma.interface MyInterface { fun doSomething() val myProperty: String } class MyClass : MyInterface { override fun doSomething() { println("Doing something in MyClass") } override val myProperty: String = "Hello" }open class BaseClass class AnotherClass : BaseClass(), MyInterface { override fun doSomething() { println("Doing something in AnotherClass") } override val myProperty: String = "World" } - Realizācijas deleģēšana: Saskarne tiek deleģēta citam objektam. Tiek izmantots vārds
by. Tas ir noderīgi kompozīcijai un vairākmantošanas problēmu novēršanai.Šajā gadījumāinterface DelegatedInterface { fun performAction() } class DelegatedObject : DelegatedInterface { override fun performAction() { println("Action performed by DelegatedObject") } } class ImplementingClass(di: DelegatedInterface) : DelegatedInterface by di { // ImplementingClass deleģē `performAction()` metodes realizāciju objektam di }ImplementingClassneizpildaperformActionpats, tā vietā izsaukumsperformingClass.performAction()tiek novirzīts uzdi.performAction().
Ja realizējat vairākas saskarnes ar vienādiem locekļiem, ir jāatrisina konflikti, skaidri pārrakstot locekli un norādot, no kura interfeisa tiek ņemta realizācija, izmantojot <Interfeiss>.<loceklis> sintaksi.
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() // Izsauc `foo` realizāciju no InterfaceA
super<InterfaceB>.foo() // Izsauc `foo` realizāciju no InterfaceB
}
override fun bar() {
super<InterfaceB>.bar() // Izmanto `bar` realizāciju no InterfaceB
}
}