Skip to content

Instantly share code, notes, and snippets.

@ragunathjawahar
Last active April 22, 2021 08:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ragunathjawahar/40e5092e14d137fb77c12cd6ea454e08 to your computer and use it in GitHub Desktop.
Save ragunathjawahar/40e5092e14d137fb77c12cd6ea454e08 to your computer and use it in GitHub Desktop.
Mini-refactoring challenge 1: Friends & Pets
/*
* ~ 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