Hi everybody, Is the logic of the delegate in C# a...
# getting-started
t
Hi everybody, Is the logic of the delegate in C# and the delegate in Kotlin the same?
t
Kotlin has 2 types of delegates : • Interface delegation • Property delegates I don't know C#, but from the few I read, C# delegates are more akin to function references, which is a completely different thing.
t
hi @tseisel In C#, delegations are variables that hold methods. It can be accessed without creating an object from the class. So what does it do in Kotlin? Can you tell in an example scenario? A scenario that can be experienced in real practice?
s
Hi Tariyel, there are several ways to instanciate methods without instanciating a class:
Copy code
fun main() {
    val spacePrinter: ()->Unit = ::printSpace      // function tearoff
    val worldPrinter: ()->Unit = {print("world")}  // lambda
    
    printHello()
    spacePrinter()
    worldPrinter()
    SomeClass.printExclamationMarks()
}

fun printHello() {
    print("hello ")
}

fun printSpace() {
    print(" ")
}

class SomeClass {
    companion object {
        fun printExclamationMarks() {
            print("!!!")
        }
    }
}
you can run the code here: https://pl.kotl.in/6TIZ2-Jmf
t
Hi @Stephan Schroeder Actually I wrote code like this for it
Copy code
class Event<T> {
    private val observers = mutableSetOf<(T) -> Unit>()

    operator fun plusAssign(observer: (T) -> Unit) {
        observers.add(observer)
    }

    operator fun minusAssign(observer: (T) -> Unit) {
        observers.remove(observer)
    }

    operator fun invoke(value: T) {
        for (observer in observers)
            observer(value)
    }
}
and I use it like this
Copy code
object GameManager {
    
    val state = Event<GameState>()

}

class Player : Move{

    init {
        GameManager.state+= ::onGameStateChanged
    }
But i want to understand what does the delegate do? What is it used for?
m
There is no "delegate" in this case (or that might be the language difference between C# and Kotlin). Event seems to be a class that holds multiple "functions" that need to be invoked with the given parameter when event itself is invoked.
Copy code
GameManager.state += ::OnGameStateChanged
will add the function
OnGameStateChanged(gameState: GameState)
to the set of events. By declaring it
::
you effectively reference a function without invoking it.
From what I can tell what you wrote, yes, ::OnGameStateChanged is akin to
In C#, delegations are variables that hold methods.
It "holds" the method, but doesn't execute it yet unless you later do so.