[Android] Set of Conditions with Koin

warunee khammak
2 min readMar 17, 2022

create functions that validate animal species

  1. create an interface to handle
interface AnimalHandler {

/***
*
@return true end loop
*
@return false continue loop
*/
fun validate(legs: Int): Boolean
}

2. create a class to handle return boolean after validating (loop of condition)

class AnimalSpeciesHandler(
val validator: Set<AnimalHandler>
) : AnimalHandler{

override fun validate(legs: Int): Boolean {
return validator.firstOrNull {
it
.validate(legs)
} != null
}
}

3. create classes to verify the type of species. for example bird and dog

class Bird(
private val source: MySource
) : AnimalHandler {

override fun validate(legs: Int): Boolean {
return source.legs == legs
}
}
class Dog(
private val source: MySource
) : AnimalHandler {

override fun validate(legs: Int): Boolean {
return source.legs == legs
}
}

4. create the module

val animalModule = module {

factory {
setOf(
get<Bird>(),
get<Dog>()
)
}

factory<AnimalHandler> { AnimalSpeciesHandler(validator = get())}
factory { Bird(source = get()) }
factory { Dog(source = get()) }
}

5. how to use inject AnimalHandler(interface) to viewModel and call the function

val inputLegs = 4
val isAnimal = animalHandler.validate(inputLegs)
if(isAnimal) {
println("It's an animal)
} else {
println("It's an animal)
}

6. in advance you can throw an Exception and add action including parameter

class Cat(
private val source: MySource
) : AnimalHandler {

override fun validate(legs: Int, isFlexibleBody: Boolean): Boolean {
return isItCat(legs, isFlexibleBody)
}
private fun isItCat(legs: Int, isFlexibleBody: Boolean) {
return if(source.legs == legs && !isFlexibleBody) {
println("It's might be Dog")
} else {
throw AlienException("Cat")
}
}
}

6.1 create Exception

class AlienException(val species: String) : Exception()

6.2 how to use

try {
val inputLegs = 4
val isAnimal = animalHandler.validate(inputLegs, true)
}
catch (e: AlienException) {
println("It's not ${e.species}, it's an alien.")
}

yes, cats are aliens.

--

--