Τι είναι οι επεκτάσεις στη γλώσσα προγραμματισμού Kotlin;
sobes.tech AI
Απάντηση από AI
Extensions in Kotlin allow adding new functions or properties to existing classes without inheritance or using decorators.
Main concepts:
-
Extension functions: Add new methods to classes.
// Definition of an extension function fun String.removeWhitespaces(): String { return this.filter { it.isWhitespace().not() } } // Usage of the extension function val myString = " Hello World " val cleanedString = myString.removeWhitespaces() // cleanedString will be "HelloWorld"The
thiskeyword inside the extension function refers to the object on which the extension is called (in the example above,myString). -
Extension properties: Allow adding new properties to classes, but cannot have state, i.e., cannot store data. They are computed on each access.
// Definition of an extension property val <T> List<T>.lastIndex: Int get() = size - 1 // Usage of the extension property val myList = listOf(1, 2, 3) val indexLast = myList.lastIndex // indexLast will be 2Extension properties must have a getter. Setter is optional.
Features:
-
Static dispatch: The call to an extension is determined by the type of the variable, not by the runtime type of the object. This differs from virtual methods in object-oriented programming.
open class Parent class Child : Parent() fun Parent.printType() = println("Parent") fun Child.printType() = println("Child") val p: Parent = Child() p.printType() // Will print "Parent", because the type of variable 'p' is Parent -
Private and protected members: Extensions cannot access private or protected members of the class they extend.
-
Extensions in companion objects: You can extend the companion objects of a class.
class MyClass { companion object { fun create() = MyClass() } } fun MyClass.Companion.printName() = println("MyClass Companion") MyClass.printName() // Will print "MyClass Companion" -
Visibility: Extensions must be declared in a file and then imported for use in other files.
Extensions are a powerful tool for creating readable and flexible code, allowing to add functionality to classes from third-party libraries without changing their source code.