Last active
April 22, 2021 08:13
-
-
Save ragunathjawahar/40e5092e14d137fb77c12cd6ea454e08 to your computer and use it in GitHub Desktop.
Mini-refactoring challenge 1: Friends & Pets
This file contains 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
/* | |
* ~ Mini-refactoring challenge 1: Friends & Pets ~ | |
* Courtesy of https://twitter.com/ragunathjawahar | |
* | |
* Instruction | |
* =========== | |
* 1. Copy and paste the contents of this gist into a new file inside any open Kotlin project in your IDE. | |
* 2. Delete it after you're done with the challenge. | |
* | |
* Objective | |
* ========= | |
* - Extract the logic within the lambda on line 27 as a function and move it to the `Friend` class. | |
* | |
* Rules for this challenge | |
* ======================== | |
* - You can't edit the source code inside the editor, that includes deleting characters. | |
* - You are allowed one copy-paste action. | |
* - You are allowed to use the keyboard for shortcuts and navigation. | |
* - Zero compilation errors during the process. | |
*/ | |
import Pet.Cat | |
import Pet.Dog | |
import Pet.Parrot | |
private fun friendsWithDogs(): List<Friend> { | |
return getFriends() | |
.filter { it.pets.isNotEmpty() /* Objective: Move this logic into the `Friend` class! 😉 */ } | |
.filter { it.pets.any { pet -> pet is Dog } } | |
} | |
data class Friend(val name: String, val pets: List<Pet>) { | |
constructor(name: String, pet: Pet) : this(name, listOf(pet)) | |
constructor(name: String) : this(name, emptyList()) | |
} | |
// ~~~ Don't change anything below this line ~~~ // | |
fun main() { | |
friendsWithDogs() | |
.onEach { println(it.name) } | |
} | |
sealed class Pet(open val name: String) { | |
data class Dog(override val name: String) : Pet(name) | |
data class Cat(override val name: String) : Pet(name) | |
data class Parrot(override val name: String) : Pet(name) | |
} | |
private fun getFriends(): List<Friend> { | |
val oreo = Dog("Oreo") | |
return listOf( | |
Friend("RMK", listOf(Dog("Raja"), Dog("Chippi"))), | |
Friend("Trisha", oreo), | |
Friend("Varsha", oreo), | |
Friend("Vinay", Cat("Blackburn")), | |
Friend("Ashish"), | |
Friend("Nethra", Parrot("Ananya")), | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment