Skip to content

Instantly share code, notes, and snippets.

@ktprezes
Created March 6, 2023 01:00
Show Gist options
  • Save ktprezes/07378d1dad7a7855ab6049b939cb44ff to your computer and use it in GitHub Desktop.
Save ktprezes/07378d1dad7a7855ab6049b939cb44ff to your computer and use it in GitHub Desktop.
Kotlin utility functions 'safeReadln()' 'String.toIntOrDefault(...)', 'String.toDoubleOrDefault(...)'
// package some_kotlin_utils
/**
* handles the 'end of stream (EOF) case' - e.g. when the user presses "Ctrl-D" instead of typing a string;
* in this case returns the passed default value (e.g. "") instead of throwing an exception as 'plain' readln() does
*
* @param default String value returned when exception occurred
* @param printErrMsg Boolean when true prints the message connected with an exception to 'stderr'
*
* @return the user-entered string or the passed default value when an exception occurred
*/
fun safeReadln(default: String = "", printErrMsg: Boolean = false) = try {
readln().trim()
} catch (e: Exception) {
if (printErrMsg)
System.err.println(e)
default
} // safeReadln(...)
/**
* example String-extension conversion functions returning some default value instead of 'null'
*/
fun String.toIntOrDefault(default: Int = Int.MIN_VALUE) = this.toIntOrNull() ?: default
fun String.toLongOrDefault(default: Long = Long.MIN_VALUE) = this.toLongOrNull() ?: default
fun String.toDoubleOrDefault(default: Double = Double.NaN) = this.toDoubleOrNull() ?: default
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment