Last active
December 10, 2019 20:35
-
-
Save juan-medina/6e4394323e800f8a6fa641db02b34126 to your computer and use it in GitHub Desktop.
persons.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| data class Person(var name: String, var age: Int) | |
| class PersonContainer { | |
| private val list = arrayListOf<Person>() | |
| fun add(person: Person) = list.add(person) | |
| fun get(): List<Person> = list | |
| infix fun String.with(age: Int) = Person(this, age) | |
| } | |
| fun persons(init: PersonContainer.() -> Unit): List<Person> { | |
| val bundle = PersonContainer() | |
| bundle.apply(init) | |
| return bundle.get() | |
| } | |
| fun PersonContainer.add(block: () -> Person) { | |
| val holder = block() | |
| this.add(Person(holder.name, holder.age)) | |
| } | |
| fun main() { | |
| val persons = persons { | |
| add { "juan" with 42 } | |
| add { "peter" with 35 } | |
| } | |
| print(persons) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment