Delegated function

3 0 0
                                        

A delegate class is a representative or a helper class. You need this delegate class as a representative to do all the work for your class. You used a "by" keyword during inheritance to transfer all the work to this delegate class.

syntax:

    interface YourBoss{ // statement }

    class YourClass(boss: YourBoss): YourBoss by boss

    class YourMaid: YourBoss { // statement}

when invoking...

    val maid = YourMaid()

    val you = YourClass(maid)


Note: It is like saying, if you knew someone who has this same idea as you, just say, "He said it all. We literally have the same idea." 

======================

fun main(){

    val rep = YourRepresentative()

    val del = JustForDelegation(rep)

    del.displayBookInfo()

}

interface Book{

    fun displayBookInfo()

}

class JustForDelegation(book: Book): Book by book

class YourRepresentative(

    var title: String = "Slime"

    var author: String = "Rimuru"

): Book{

    override fun displayBookInfo(){

        println("$author wrote $title.")

    }

}

======================

Result:

Rimuru wrote Slime.


Note: You can just override the abstract function in your own class while delegating. And the compiler will invoke this override function rather than the function in delegate class but what is the point of you asking for help without using it.

Kotlin ProgrammingWhere stories live. Discover now