Also remember that you are not limited to just one delegate. The Kotlin delegation implementation method is similar to traits implementation in languages โโsuch as Groovy. You can create various functions through delegates. The Kotlin method can also be considered more powerful, because you can also โplug inโ various implementations.
interface Marks { fun printMarks() } class StdMarks() : Marks { override fun printMarks() { println("printed marks") } } class CsvMarks() : Marks { override fun printMarks() { println("printed csv marks") } } interface Totals { fun printTotals() } class StdTotals : Totals { override fun printTotals() { println("calculated and printed totals") } } class CheatTotals : Totals { override fun printTotals() { println("calculated and printed higher totals") } } class Student(val studentId: Int, marks: Marks, totals: Totals) : Marks by marks, Totals by totals fun main(args:Array<String>) { val student = Student(1,StdMarks(), StdTotals()) student.printMarks() student.printTotals() val cheater = Student(1,CsvMarks(), CheatTotals()) cheater.printMarks() cheater.printTotals() }
Output:
printed marks calculated and printed totals printed csv marks calculated and printed higher totals
You cannot do this with inheritance.
source share