Tariyel Islami
05/01/2022, 7:18 PMtseisel
05/02/2022, 4:30 PMTariyel Islami
05/02/2022, 9:55 PMStephan Schroeder
05/03/2022, 7:23 AMfun 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-JmfTariyel Islami
05/03/2022, 7:05 PMclass 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
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?Michael de Kaste
05/04/2022, 9:06 AMGameManager.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.In C#, delegations are variables that hold methods.It "holds" the method, but doesn't execute it yet unless you later do so.