Skip to content

Instantly share code, notes, and snippets.

@jmfayard
Last active February 5, 2018 08:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmfayard/05196271298ac067272b6c26a577a00b to your computer and use it in GitHub Desktop.
Save jmfayard/05196271298ac067272b6c26a577a00b to your computer and use it in GitHub Desktop.
// https://medium.com/@garnop/safe-concise-text-parsing-with-regex-destructuring-in-kotlin-b8f77ef1e30c
fun parsePhoneNumber(input: String): PhoneNumber {
val invalids = input.filterNot { it in '0'..'9' || it == '-' }
require(invalids.isEmpty()) { "Input $input has invalid characters : $invalids" }
val (areaCode, prefix, lineNumber) = input.split("-").map(String::toInt)
return PhoneNumber(areaCode, prefix, lineNumber)
}
fun main(args: Array<String>) {
val input =
require(parsePhoneNumber("888-888-8888") == PhoneNumber(888, 888, 8888))
}
data class PhoneNumber(
val areaCode: Int,
val prefix: Int,
val lineNumber: Int
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment