Kotlin mutablelist to immutable

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Immutable persistent collections for Kotlin

License

Kotlin/kotlinx.collections.immutable

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

`toImmutable()` -> `toImmutableList()`

Git stats

Files

Failed to load latest commit information.

README.md

Immutable Collections Library for Kotlin

Immutable collection interfaces and implementation prototypes for Kotlin.

This is a multiplatform library providing implementations for jvm , js (both Legacy and IR), mingwX64 , linuxX64 and Apple Kotlin/Native targets.

For further details see the proposal.

Interfaces and implementations

This library provides interfaces for immutable and persistent collections.

Immutable collection interfaces

Interface Bases
ImmutableCollection Collection
ImmutableList ImmutableCollection , List
ImmutableSet ImmutableCollection , Set
ImmutableMap Map

Persistent collection interfaces

Interface Bases
PersistentCollection ImmutableCollection
PersistentList PersistentCollection , ImmutableList
PersistentSet PersistentCollection , ImmutableSet
PersistentMap ImmutableMap

Persistent collection builder interfaces

Interface Bases
PersistentCollection.Builder MutableCollection
PersistentList.Builder PersistentCollection.Builder , MutableList
PersistentSet.Builder PersistentCollection.Builder , MutableSet
PersistentMap.Builder MutableMap

To instantiate an empty persistent collection or a collection with the specified elements use the functions persistentListOf , persistentSetOf , and persistentMapOf .

The default implementations of PersistentSet and PersistentMap , which are returned by persistentSetOf and persistentMapOf , preserve the element insertion order during iteration. This comes at expense of maintaining more complex data structures. If the order of elements doesn’t matter, the more efficient implementations returned by the functions persistentHashSetOf and persistentHashMapOf can be used.

Converts a read-only or mutable collection to an immutable one. If the receiver is already immutable and has the required type, returns it as is.

fun Iterable.toImmutableList(): ImmutableListT> fun Iterable.toImmutableSet(): ImmutableSetT>

Converts a read-only or mutable collection to a persistent one. If the receiver is already persistent and has the required type, returns it as is. If the receiver is a builder of the required persistent collection type, calls build on it and returns the result.

fun Iterable.toPersistentList(): PersistentListT> fun Iterable.toPersistentSet(): PersistentSetT>

plus and minus operators on persistent collections exploit their immutability and delegate the implementation to the collections themselves. The operation is performed with persistence in mind: the returned immutable collection may share storage with the original collection.

val newList = persistentListOf("a", "b") + "c" // newList is also a PersistentList

Note: you need to import these operators from kotlinx.collections.immutable package in order for them to take the precedence over the ones from the standard library.

import kotlinx.collections.immutable.*

mutate extension function simplifies quite common pattern of persistent collection modification: get a builder, apply some mutating operations on it, transform it back to a persistent collection:

collection.builder().apply < some_actions_on(this) >.build()

With mutate it transforms to:

Note that the library is experimental and the API is subject to change.

The library is published to Maven Central repository.

The library depends on the Kotlin Standard Library of the version at least 1.6.0 .

Add the Maven Central repository:

Add the library to dependencies of the platform source set, e.g.:

kotlin < sourceSets < commonMain < dependencies < implementation("org.jetbrains.kotlinx:kotlinx-collections-immutable:0.3.5") > > > >

The Maven Central repository is available for dependency lookup by default. Add dependencies (you can also add other modules that you need):

dependency> groupId>org.jetbrains.kotlinxgroupId> artifactId>kotlinx-collections-immutable-jvmartifactId> version>0.3.5version> dependency>

You can build and install artifacts to maven local with:

Источник

[Solved]-How to turn a Mutable Collection into an Immutable one-kotlin

Currently in Kotlin stdlib there are no implementations of List ( Map ) that would not also implement MutableList ( MutableMap ). However due to Kotlin’s delegation feature the implementations become one liners:

class ImmutableList(private val inner:List) : List by inner class ImmutableMap(private val inner: Map) : Map by inner 

You can also enhance the creation of the immutable counterparts with extension methods:

fun Map.toImmutableMap(): Map < if (this is ImmutableMap) < return this >else < return ImmutableMap(this) >> fun List.toImmutableList(): List < if (this is ImmutableList) < return this >else < return ImmutableList(this) >> 

The above prevents a caller from modifying the List ( Map ) by casting to a different class. However there are still reasons to create a copy of the original container to prevent subtle issues like ConcurrentModificationException:

class ImmutableList private constructor(private val inner: List) : List by inner < companion object < fun create(inner: List) = if (inner is ImmutableList) < inner >else < ImmutableList(inner.toList()) >> > class ImmutableMap private constructor(private val inner: Map) : Map by inner < companion object < fun create(inner: Map) = if (inner is ImmutableMap) < inner >else < ImmutableMap(hashMapOf(*inner.toList().toTypedArray())) >> > fun Map.toImmutableMap(): Map = ImmutableMap.create(this) fun List.toImmutableList(): List = ImmutableList.create(this) 

While the above is not hard to implement there are already implementations of immutable lists and maps in both Guava and Eclipse-Collections.

If you need to convert MutableMap strictly to ImmutableMap , this will not work

val iMap : ImmutableMap = mutMap.toMap() // error 

I have found the only working way:

val iMap : ImmutableMap = ImmutableMap.builder().putAll(mutMap).build() 

Use simple bellow codes to convert Mutable Collections into an Immutable one:

val mutableList = mutableListOf() val immutableList: List = mutableList 

AlirezA Barakati 715

A classic solution is to copy your data, so that even if modified, the change would not affect the private class property:

class School < private val roster = mutableMapOf>() fun db(): Map> = roster.mapValuestTo > 

voddan 29018

I know this a Kotlin specific question and @Malt is correct but I would like to add an alternative. In particular I find Eclipse Collections, formally GS-Collections, as a better alternative to Guava for most cases and it supplements Kotlin’s built in collections well.

Simply call toMap() on your MutableMap .

val myMap = mutableMapOf("x" to "y").toMap() 

The same also works for lists.

Renann 524

As mentioned here and here, you’d need to write your own List implementation for that, or use an existing one (Guava’s ImmutableList comes to mind, or Eclipse Collections as Andrew suggested).

Kotlin enforces list (im)mutability by interface only. There are no List implementations that don’t also implement MutableList .

Even the idiomatic listOf(1,2,3) ends up calling Kotlin’s ArraysUtilJVM.asList() which calls Java’s Arrays.asList() which returns a plain old Java ArrayList .

If you care more about protecting your own internal list, than about the immutability itself, you can of course copy the entire collection and return it as an List , just like Kotlin does:

Malt 27499

Use Collections to converts a Mutable list to Immutable list, Example:

val mutableList = mutableListOf() 

Converts to Immutable list:

val immutableList = Collections.unmodifiableList(mutableList) 

Benny 1908

  • How to turn a Mutable Collection into an Immutable one
  • How to add String Array and Integer Array from XML into one Collection
  • How to add values to a mutable list to then add to an immutable one
  • How can I combine two arrays into one array in Kotlin?
  • How to get result of two mutablelivedata into one
  • How to covert a Java collection into a Kotlin Sequence (and vice versa) in Java?
  • Is there a collection function like map to turn every item in a list into two items?
  • RxJava2 how to join 2 Single List into one list
  • Kotlin: return immutable collection from getter while using mutable inside
  • Kotlin: how to pass collection into generic type of a function
  • Mutable and immutable collection classes are the same kotlin
  • Kotlin — How to convert a list of objects into a single one after map operation?
  • Kotlin: adding a mutable list into 2D mutable list duplicate it’s previous lists to the newly added one
  • How can split a string which include only one hyperlink into multiple segments in Kotlin?
  • How to combine multiple mp4 videos into one video using jcodec in Java?
  • MapStruct in Kotlin: How to map from multiple sources into one model?
  • How to deserialize an array of values into a collection using kotlinx serialization
  • How can I gather data across multiple async sources into a kotlin data class with immutable properties?
  • How can I turn a txt file into a string just using its path?
  • How to combine several annotation into one in Kotlin?
  • How to combine following Observables into one in Kotlin?
  • How to extract Map from collection of objects, with the key as one of the objects same field and value the actual objects
  • How do I turn all of a webview content into a bitmap?
  • How can I turn .apply in kotlin into java, I can’t find .apply in java at all
  • How can I turn this into a lambda?
  • How to merge two different classes data into one in Kotlin
  • How to move a firestore document from one collection to another
  • How do I split one string into two strings in Kotlin with «.»?
  • How to Merge multiple Observables with diferents call backs into one single Stream?
  • How to add contents of one collection to a new collection

More Query from same tag

  • Why does gradle init generate variable mainClass, while mainClassName is needed?
  • RecyclerView doesn’t display data but onBindViewHolder never called
  • setStartLineColor and setEndLineColor not working for timeline view
  • Android locale file not loaded
  • Kotlin buildscript not using my custom maven repo
  • My application runs fine on Android 10 but crashes on all other Android versions. In the emulator AND on the real device
  • split string between 2 char based index
  • How to place a View on a certain map location of GoogleMap?
  • Reduce/Collect `List` to `Map>`
  • Coroutine Channel in Extension Class does not send or receive data
  • Android OkHttpClient — download file with Kotlin
  • Refactor code to not throw Mockito’s UnnecessaryStubbingException
  • Why is Kotlin’s Number-class missing operators?
  • Different objects in one when statement (kotlin)
  • Duplicates values in Map: Kotlin
  • Click event using DataBinding Library inside Recyclerview’s adapter
  • Type mismatch: inferred type is String but Int was expected
  • OnClick not called while I get OnTouch event
  • recyclerview not visible at run time
  • Read values from concrete BLE characteristic Kotlin
  • Hibernate and using @GeneratedValue with CockroachDB results in SQLGrammarException
  • Different result when sorting list with same elements and order
  • Android-XML custom spinner
  • Kotlin: const val vs val
  • How mock Companion object in Android using Mockito
  • How to store BigDecimal in Firebase?
  • What kind of implementation that can get all the SubProjects in each IncludedBuilds in Gradle with the customized tasks?
  • Unit testing WebFlux Routers with Spek
  • I want to have a minigame inside my notetaking application in android
  • How can you set the default value for array parameters in Kotlin?

Источник

Читайте также:  Run cpp file windows
Оцените статью