1
0
mirror of https://github.com/mamoe/mirai.git synced 2025-04-25 21:12:40 +08:00

Add Collection.asImmutable for commonMain

This commit is contained in:
Him188 2022-05-25 19:49:29 +01:00
parent 2396851b63
commit 0f9e7e2742
No known key found for this signature in database
GPG Key ID: BA439CDDCF652375
3 changed files with 36 additions and 14 deletions
mirai-core-utils/src
commonMain/kotlin
jvmBaseMain/kotlin
nativeMain/kotlin

View File

@ -71,4 +71,16 @@ public fun <K, V : R, R> Map<K, V>.getOrDefault(key: K, default: R): R = getOrEl
@Suppress("EXTENSION_SHADOWED_BY_MEMBER") // JDK 1.8
@Deprecated("", ReplaceWith("getOrPut(key) { value }"))
public fun <K, V> MutableMap<K, V>.putIfAbsent(key: K, value: V): V = getOrPut(key) { value }
public fun <K, V> MutableMap<K, V>.putIfAbsent(key: K, value: V): V = getOrPut(key) { value }
/**
* Returns a [List] that cannot be cast to [MutableList] to modify it.
*/
public expect fun <T> List<T>.asImmutable(): List<T>
/**
* Returns a [Collection] that cannot be cast to [MutableCollection] to modify it.
*/
public expect fun <T> Collection<T>.asImmutable(): Collection<T>
public expect fun <T> Set<T>.asImmutable(): Set<T>

View File

@ -14,26 +14,17 @@ import java.util.concurrent.CopyOnWriteArraySet
import kotlin.reflect.KClass
public fun <T> Collection<T>.asImmutable(): Collection<T> {
return when (this) {
is List<T> -> asImmutable()
is Set<T> -> asImmutable()
else -> Collections.unmodifiableCollection(this)
}
}
@Suppress("NOTHING_TO_INLINE")
public inline fun <T> Collection<T>.asImmutableStrict(): Collection<T> {
public actual fun <T> Collection<T>.asImmutable(): Collection<T> {
return Collections.unmodifiableCollection(this)
}
@Suppress("NOTHING_TO_INLINE")
public inline fun <T> List<T>.asImmutable(): List<T> {
public actual inline fun <T> List<T>.asImmutable(): List<T> {
return Collections.unmodifiableList(this)
}
@Suppress("NOTHING_TO_INLINE")
public inline fun <T> Set<T>.asImmutable(): Set<T> {
public actual inline fun <T> Set<T>.asImmutable(): Set<T> {
return Collections.unmodifiableSet(this)
}

View File

@ -90,4 +90,23 @@ public actual interface MutableQueue<E> : MutableCollection<E> {
public actual fun offer(element: E): Boolean
}
}
/**
* Returns a [List] that cannot be cast to [MutableList] to modify it.
*/
public actual fun <T> List<T>.asImmutable(): List<T> = ImmutableList(this)
public actual fun <T> Collection<T>.asImmutable(): Collection<T> = ImmutableCollection(this)
public actual fun <T> Set<T>.asImmutable(): Set<T> = ImmutableSet(this)
internal class ImmutableList<T>(
private val delegate: List<T>
) : List<T> by delegate
internal class ImmutableCollection<T>(
private val delegate: Collection<T>
) : Collection<T> by delegate
internal class ImmutableSet<T>(
private val delegate: Set<T>
) : Set<T> by delegate