Last active
December 14, 2018 13:20
-
-
Save noiaverbale/f5ab549bb00e498f970d07a24850e1b7 to your computer and use it in GitHub Desktop.
The position class of a chess game in kotlin
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
internal data class Position(val name: String) { | |
constructor(file: Int, rank: Int) : this("${(file + 'A'.toInt()).toChar()}${rank + 1}") | |
val file: Int = name.validateAndTransform { it[0] - 'A' } | |
val rank: Int = name.validateAndTransform { it[1].toString().toInt() - 1 } | |
private fun <T> String.validateAndTransform(trasformer: (String) -> T): T = | |
if (Regex("""^[A-H][1-8]$""") matches this) | |
trasformer(this) | |
else | |
throw IllegalStateException("position name must be of one letter from A to H and one number from 1 to 8") | |
/** | |
* @return the name of this position | |
*/ | |
override fun toString() = name | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment