Useful Kotlin extensions
repositories {
mavenCentral()
}
dependencies {
implementation("dev.botta:kotlin-extensions:1.0.2")
}
repositories {
mavenCentral()
}
dependencies {
implementation 'dev.botta:kotlin-extensions:1.0.2'
}
<dependency>
<groupId>dev.botta</groupId>
<artifactId>kotlin-extensions</artifactId>
<version>1.0.2</version>
</dependency>
fun Any?.ifNull(block: () -> Unit)
fun <T: Any> T?.ifNotNull(block: (T) -> Unit)
fun Any?.throwIfNull(block: (T) -> Throwable)
user.ifNull { println("User is null") }
user.ifNotNull { println("User is not null") }
user.throwIfNull { UserRequiredError() }
fun Boolean.ifTrue(block: () -> Unit)
fun Boolean.ifFalse(block: () -> Unit)
fun Boolean.throwIfTrue(block: () -> Throwable)
fun Boolean.throwIfFalse(block: () -> Throwable)
condition.ifTrue { println("Condition is true") }
condition.ifFalse { println("Condition is false") }
(fromDate > toDate).throwIfTrue { InvalidDateRange() }
(fromDate < toDate).throwIfFalse { InvalidDateRange() }
fun T.alsoIf(condition: Boolean, block: (T) -> Unit)
User().alsoIf(addUser) { userRepository.add(it) }
fun <T> Iterable<T>.each(action: (T) -> Unit)
users.each { println(it.name)}
fun List<Any>.stringArray(): Array<String>
fun String.toSnakeCase(): String
fun String?.throwIfNullOrBlank(block: () -> Throwable)
fun String.lastWord()
"myName".toSnakeCase() // returns "my_name"
email.throwIfNullOrBlan { EmailRequiredError() }
"Some sentence".lastWord() // returns "sentence"
var user by mutableLazy { fetchUser() }
user = fetchOtherUser()
fun address(addDetails: DetailsExt<AddressBuilder>): Address {
return AddressBuilder().also(addDetails).build()
}
val myAddress = address { street("Western Avenue"); city("New York") }