Created
October 26, 2024 10:59
-
-
Save Vadym-Lopatka/7f09908ab3a7431a27028da2abacac1f to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| 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