In this example, I have share how kotlin delegation is useful? Also remember that you’re not restricted to just one delegate. Kotlin’s way of implementing delegation is similar to traits implementation in languages like Groovy. You can compose different functionality via delegates. Kotlin’s way can also be considered more powerful because you can “plug in” different implementations too.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | 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
1 2 3 4 | printed marks calculated and printed totals printed csv marks calculated and printed higher totals |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.