Delegating Delegates to Kotlin #1 (by)

Dmitry Klokov·2021년 1월 7일
0

KOTLIN

목록 보기
2/6
post-thumbnail

Medium | Delegate Kotlin #1

Medium | Delegate Kotlin #2


Kotlin Vocabulary: Delegates

  • Delegating work from one object to another.

  • Delegation is a design pattern in which an object handles a request by delegating to a helper object, called the delegate.

  • The delegate is responsible for handling the request on behalf of the original object and making the results available to the original object.

  • Kotlin makes delegation easier by providing support for class and property delegates and even containing some built-in delegates of its own.

Class Delegates

class ListWithTrash<T>(
        private val innerList: MutableList<T> = ArrayList<T>()
    ) : MutableCollection<T> by innerList {
        var deletedItem: T? = null
        override fun remove(element: T): Boolean {
            deletedItem = element
            return innerList.remove(element)
        }
        fun recover(): T? = deletedItem
    }
  • The by keword tells Kotlin to delegate functionality from the MutableList interface to an internal ArrayList instance named innerList.

  • ListWithTrash still supports all the functions in the MutalbeList interface by providing direct bridge methods to the interal ArrayList object.

  • Plus, now you have the ability to add your own behavior.

Delegating properties

private class Person(name: String, lastname: String) {
        var name: String by FormatDelegate()
        var lastname: String by FormatDelegate()
        var updateCount = 0
}
private class FormatDelegate : ReadWriteProperty<Any?, String> {

        private var formattedString: String = ""

        override fun getValue(
            thisRef: Any?,
            property: KProperty<*>
        ): String {
            if (thisRef is Person) {
                thisRef.updateCount++
            }
            return formattedString
        }

        override fun setValue(
            thisRef: Any?,
            property: KProperty<*>,
            value: String) {
            if (thisRef is Person) {
                thisRef.updateCount++
            }
            formattedString = value.toLowerCase().capitalize()
        }

    }

Summary

  • Delegates can help you delegate tasks to other objects and provide better code reuse.

  • The Kotlin compiler creates the code to let you use delegates seamlessly.

  • Kotlin uses simple syntax with the by keyword to delegate a property or a class.

  • Under the hood, the Kotlin compiler generates all the necessary code to support delegation without exposing any change to the public API.

  • Simply put, Kotlin generates and maintains all the needed boilerplate code for delegates, or in other words, you can delegate your delegates to Kotlin.

profile
Power Weekend

0개의 댓글

관련 채용 정보