Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@amir-dropit
Last active December 1, 2021 14:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save amir-dropit/8aed112fa1004d231fd1b15917f03420 to your computer and use it in GitHub Desktop.
Save amir-dropit/8aed112fa1004d231fd1b15917f03420 to your computer and use it in GitHub Desktop.
Kotlin delegates examples

Some Kotlin delegates examples

  • property delegates and class delegates
class ListWithTrash<T>(
private val innerList: MutableList<T> = ArrayList()
) : MutableList<T> by innerList {
var deletedItem: T? = null
fun recover() = deletedItem
override fun remove(element: T): Boolean {
deletedItem = element
return innerList.remove(element)
}
override fun removeAt(index: Int): T {
return innerList.removeAt(index).also {
deletedItem = it
}
}
}
fun main() {
val lista = ListWithTrash<String>(arrayListOf("One","Two","Three"))
lista.removeAt(1)
println(lista.recover())
}
import java.net.NetworkInterface
import kotlin.properties.Delegates
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
class PropertyDelegates {
val stream: NetworkInterface by lazy {
NetworkInterface.getNetworkInterfaces().asSequence().first { it.isUp }
}
var subscibers: Number by Delegates.observable(0) { property, oldValue, newValue ->
println("${property.name} has been changed from $oldValue to $newValue")
}
var counter: Int by Delegates.vetoable(0){ property, oldValue, newValue ->
return@vetoable if (newValue > oldValue) true else throw IllegalArgumentException("New value must be larger than old value")
}
var id: Int by Delegates.notNull()
fun initialize(_id: Int){
id = _id
}
}
class Person(_firstName: String, _lastName: String){
var firstName: String by NameFormatter(_firstName)
var lastName: String by NameFormatter(_lastName)
}
class NameFormatter(initialValue: String): ReadWriteProperty<Person,String>{
private var formattedValue: String = format(initialValue)
override fun getValue(thisRef: Person, property: KProperty<*>): String = formattedValue
override fun setValue(thisRef: Person, property: KProperty<*>, value: String) {
formattedValue = format(value)
}
private fun format(value: String): String{
return value.trim().lowercase().capitalize()
}
}
fun main() {
val person = Person("jOhnnY ","depp")
println("${person.firstName} ${person.lastName}")
}
data class Author(val id: String,val name: String,val books: List<String>)
data class Book(val id: String,val name: String, val author: String)
interface AuthorsRepository{
fun getAuthorById(id: String): Author
fun getAuthorByName(id: String): Author
fun getAllAuthors(): List<Author>
}
interface BooksRepository{
fun getBookById(id: String): Book
fun getBookByName(id: String): Book
fun getAllBooks(): List<Book>
}
class AuthorsRepositoryImpl: AuthorsRepository{
val someAuthor = Author(id = "23rfdfsd",name = "Herman Smallville", listOf("4ffssds3"))
override fun getAuthorById(id: String): Author {
return someAuthor
}
override fun getAuthorByName(id: String): Author {
return someAuthor
}
override fun getAllAuthors(): List<Author> {
return listOf(someAuthor)
}
}
class BooksRepositoryImpl: BooksRepository{
val someBook = Book(id = "4ffssds3",name = "Bobby Dick", "23rfdfsd")
override fun getBookById(id: String): Book {
return someBook
}
override fun getBookByName(id: String): Book {
return someBook
}
override fun getAllBooks(): List<Book> {
return listOf(someBook)
}
}
class CatalogRepository(
private val booksRepository: BooksRepository,
private val authorsRepository: AuthorsRepository
): BooksRepository by booksRepository, AuthorsRepository by authorsRepository{
fun getBookAndAuthor(bookId: String): Pair<Book,Author>{
val book = booksRepository.getBookById(bookId)
val author = authorsRepository.getAuthorById(book.author)
return book to author
}
fun getAllBooksByAuthorName(name: String): List<Book>{
val author = authorsRepository.getAuthorByName(name)
return author.books.map { booksRepository.getBookById(it) }
}
}
fun main(){
val catalogRepository = CatalogRepository(BooksRepositoryImpl(),AuthorsRepositoryImpl())
catalogRepository.getAllBooksByAuthorName("")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment