Skip to content

Instantly share code, notes, and snippets.

@Vadym-Lopatka
Created October 26, 2024 10:59
Show Gist options
  • Select an option

  • Save Vadym-Lopatka/7f09908ab3a7431a27028da2abacac1f to your computer and use it in GitHub Desktop.

Select an option

Save Vadym-Lopatka/7f09908ab3a7431a27028da2abacac1f to your computer and use it in GitHub Desktop.
interface Animal {
fun encounter(other: Animal): Decision
}
enum class Decision { RUN_AWAY, EAT, FIGHT, MATE }
class Lion : Animal {
override fun encounter(other: Animal): Decision {
return when (other) {
is Lion -> Decision.FIGHT
is Bunny -> Decision.EAT
else -> throw IllegalArgumentException("unrecognizable type: ${other::class.simpleName}")
}
}
}
class Bunny : Animal {
override fun encounter(other: Animal): Decision {
return when (other) {
is Lion -> Decision.RUN_AWAY
is Bunny -> Decision.MATE
else -> throw IllegalArgumentException("unrecognizable type: ${other::class.simpleName}")
}
}
}
fun main() {
val b1 = Bunny()
val b2 = Bunny()
val l1 = Lion()
val l2 = Lion()
println(b1.encounter(b2)) // MATE
println(b1.encounter(l1)) // RUN_AWAY
println(l1.encounter(b1)) // EAT
println(l1.encounter(l2)) // FIGHT
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment