Skip to content

Instantly share code, notes, and snippets.

@xrrocha
Created December 16, 2020 17:26
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 xrrocha/97e7ac4f1f1271437a1d3d62d357f509 to your computer and use it in GitHub Desktop.
Save xrrocha/97e7ac4f1f1271437a1d3d62d357f509 to your computer and use it in GitHub Desktop.
code block for README-27
// Nullable constructor arg w/default
class Numberer(pattern: String? = null) {
companion object {
// Public constant
const val DEF_PATTERN = "000,000"
}
// Private field w/fallback value (?:)
private val formatter =
DecimalFormat(pattern ?: DEF_PATTERN)
fun numberLines(lines: List<String>) =
// lines.indices: 0 until lines.size
lines.indices.map { index ->
formatter.format(index + 1) +
" " + lines[index]
}
}
fun main() {
val numberer = Numberer("00")
val words = listOf(
"out", "of", "mind",
"back", "in", "five"
)
// lambda w/method reference
numberer.numberLines(words)
.forEach(::println)
/*
prints:
01 out
02 of
03 mind
04 back
05 in
06 five
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment