Skip to content

Instantly share code, notes, and snippets.

@noiaverbale
Last active December 14, 2018 13:20
Show Gist options
  • Save noiaverbale/f5ab549bb00e498f970d07a24850e1b7 to your computer and use it in GitHub Desktop.
Save noiaverbale/f5ab549bb00e498f970d07a24850e1b7 to your computer and use it in GitHub Desktop.
The position class of a chess game in kotlin
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