Hi everybody, Is the logic of the delegate in C# a...
# getting-started
Hi everybody, Is the logic of the delegate in C# and the delegate in Kotlin the same?
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.
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?
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

fun printHello() {
    print("hello ")

fun printSpace() {
    print(" ")

class SomeClass {
    companion object {
        fun printExclamationMarks() {
you can run the code here: https://pl.kotl.in/6TIZ2-Jmf
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) {

    operator fun minusAssign(observer: (T) -> Unit) {

    operator fun invoke(value: T) {
        for (observer in observers)
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?
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.