Created
September 23, 2021 15:27
-
-
Save aysesenses/7ce9906f1cefb8475ea36fcc0f6e64dd to your computer and use it in GitHub Desktop.
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
import java.util.* | |
fun main(args: Array<String>) { | |
println("Hello, ${args[0]}!") | |
feedTheFish() | |
eagerExample() | |
} | |
fun shouldChangeWater( | |
day: String, | |
temperature: Int = 22, | |
dirty: Int = 20 | |
): Boolean { | |
val isTooHot = temperature > 30 | |
val isDirty = dirty > 35 | |
val isSunday = day == "Sunday" | |
return when { | |
isTooHot(temperature) -> true | |
isDirty(dirty) -> true | |
isSunday(day) -> true | |
else -> false | |
} | |
} | |
fun isTooHot(temperature: Int) = temperature > 30 | |
fun isDirty(dirty: Int) = dirty > 30 | |
fun isSunday(day: String) = day == "Sunday" | |
fun feedTheFish() { | |
val day = randomDay() | |
val food = fishFood(day) | |
shouldChangeWater(day, 20, 50) | |
shouldChangeWater(day) | |
shouldChangeWater(day, dirty = 50) | |
if (shouldChangeWater(day)) { | |
println("Change the water today") | |
} | |
//call dirty processor | |
dirtyProcessor() | |
println("Today is $day and the fish eat $food") | |
} | |
fun randomDay(): String { | |
val week = listOf( | |
"Monday", "Tuesday", "Wednesday", | |
"Thursday", "Friday", "Saturday", "Sunday" | |
) | |
return week[Random().nextInt(7)] | |
} | |
fun fishFood(day: String): String { | |
var food = "fasting" | |
return when (day) { | |
"Monday" -> "flakes" | |
"Wednesday" -> "granules" | |
"Tuesday" -> "redwors" | |
"Friday" -> "mosquitoes" | |
"Sunday" -> "plankton" | |
else -> "fasting" | |
} | |
} | |
fun eagerExample() { | |
val decorations = listOf("rock", "pagoda", "plastic plant", "alligator", "flowerpot") | |
val eager = decorations.asSequence().filter { it[0] == 'p' } | |
print(eager) | |
//apply filter lazily | |
val filtered = decorations.asSequence().filter { it[0] == 'p' } | |
println(filtered) | |
println(filtered.toList()) | |
//apply map lazily | |
val lazyMap = decorations.asSequence().map { | |
println("map: $it") | |
it | |
} | |
println(lazyMap) | |
println("first: ${lazyMap.first()}") | |
println("all: ${lazyMap.toList()}") | |
} | |
var dirty = 20 | |
val waterFilter: (Int) -> Int = { dirty -> dirty / 2 } | |
fun feedFish(dirty: Int) = dirty + 10 | |
fun updateDirty(dirty: Int, operation: (Int) -> Int): Int { | |
return operation(dirty) | |
} | |
fun dirtyProcessor() { | |
dirty = updateDirty(dirty, waterFilter) | |
dirty = updateDirty(dirty, ::feedFish) //feedFish a name functions so use :: | |
dirty = updateDirty(dirty) { dirty -> | |
dirty + 50 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment