com.itangcent.common.utils.CollectionKit.kt Maven / Gradle / Ivy
package com.itangcent.common.utils
import java.util.*
/**
* Accumulates value starting with the first element and applying [operation] from left to right to current accumulator value and each element.
*/
inline fun Iterable.reduceSafely(operation: (acc: S, T) -> S): S? {
val iterator = this.iterator()
if (!iterator.hasNext()) return null
var accumulator: S = iterator.next()
while (iterator.hasNext()) {
accumulator = operation(accumulator, iterator.next())
}
return accumulator
}
fun Array<*>?.notNullOrEmpty(): Boolean {
return !this.isNullOrEmpty()
}
fun Collection<*>?.notNullOrEmpty(): Boolean {
return !this.isNullOrEmpty()
}
fun List.asArrayList(): ArrayList {
if (this is ArrayList) {
return this
}
return ArrayList(this)
}
private val IMMUTABLE_LIST_CLASSES = listOf(
emptyList().javaClass,
Collections.emptyList().javaClass,
Collections.singletonList("").javaClass,
)
private val IMMUTABLE_SET_CLASSES = listOf(
emptySet().javaClass,
Collections.emptySet().javaClass,
)
private val IMMUTABLE_COLLECTION_CLASSES = IMMUTABLE_LIST_CLASSES + IMMUTABLE_SET_CLASSES
fun Any.isMutableCollection(): Boolean {
if (this !is Collection<*>) return false
return !IMMUTABLE_COLLECTION_CLASSES.contains(this.javaClass)
}