Skip to content

Instantly share code, notes, and snippets.

@imashnake0
Last active January 14, 2023 02:07
Show Gist options
  • Save imashnake0/3a50df20c75f9433f0546de19436dda0 to your computer and use it in GitHub Desktop.
Save imashnake0/3a50df20c75f9433f0546de19436dda0 to your computer and use it in GitHub Desktop.
Kotlin Extensions

Kotlin Extensions

This gist will host some nice extensions for anything Kotlin.

Double.kt

/**
 * Rounds a [Double] to [numberOfPlaces].
 */
fun Double.roundTo(numberOfPlaces: Int): Double {
    return round(this*10.0.pow(numberOfPlaces))/10.0.pow(numberOfPlaces)
}

/**
 * Returns the decimal part of a [Double].
 */
val Double.decimal get() = this % toInt()

Int.kt

/**
 * Equivalent of [String.isNullOrEmpty] for [Int].
 *
 * @see [String.isNullOrEmpty]
 * @see [String.isNullOrBlank]
 */
fun Int?.isNullOrZero(): Boolean = this == 0 || this == null

FlaotToFloat.kt

/**
 * Integrate a function (lambda) from [from] to [to].
 */
fun ((Float) -> Float).integrate(
    from: Float, 
    to: Float, 
    dx: Float
): Float {
    var at = from
    var integral = 0f
    while(at < to) {
	integral += this(at) * dx
        at += dx
    }
    return integral
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment