Skip to content

Instantly share code, notes, and snippets.

@kiwiandroiddev
Last active June 1, 2016 06:04
Show Gist options
  • Select an option

  • Save kiwiandroiddev/2b4d8218c9ceef8e50a193bbfeab25ce to your computer and use it in GitHub Desktop.

Select an option

Save kiwiandroiddev/2b4d8218c9ceef8e50a193bbfeab25ce to your computer and use it in GitHub Desktop.
Small general-purpose extension functions and utilities for Kotlin
/**
* If [assumed] is non-null, converts it to a non-null type and executes [block] on the non-null
* type as an extension function (like with() in the Standard kotlin library)
*
* Similar to Swift's "if let = ..." construct.
*/
fun <T> if_let(assumed : T?, block : T.() -> Unit) {
if (assumed == null)
return
val definite : T = assumed
definite.block()
}
/**
* Returns the index of [element] in the list, or [default] if the list does not contain [element].
*/
fun <T> List<T>.indexOfOrDefault(element: T, default : Int) : Int {
val index = indexOf(element)
return if (index != -1) index else default
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment