Related
I have a very basic problem in a rust relating to mutability of objects inside a vector. I have a need to get a mutable reference to an object from within a method of the struct as follows:
struct Allocator {
free_regions: Vec<Region>, // vec of free regions
used_regions: Vec<Region>, // vec of used regions
}
fn alloc(&self, layout: Layout) -> ! {
//I want to get this mutable reference in order to avoid copying large amount of data around
let region: &mut Region = self.free_regions.get_mut(index).expect("Could not get region");
//This fails with `self` is a `&` reference, so the data it refers to cannot be borrowed as mutable
}
I cannot change the function to use &mut self because this requirement is forced by a trait I'm trying to implement here. What is a proper way to get around this kind of issue? I need to be able to modify the data in those regions inside the Vec in the struct.
You need to use RefCell, or Mutex if it is shared between threads
struct Allocator {
free_regions: RefCell<Vec<Region>>, // vec of free regions
used_regions: RefCell<Vec<Region>>, // vec of used regions
}
fn alloc(&self, layout: Layout) -> ! {
//I want to get this mutable reference in order to avoid copying large amount of data around
let region: &mut Region = self.free_regions.borrow_mut().get_mut(index).expect("Could not get region");
//This fails with `self` is a `&` reference, so the data it refers to cannot be borrowed as mutable
}
You can find more info here https://doc.rust-lang.org/book/ch15-05-interior-mutability.html
For example, given a map like below:
{
"k1": {
"k2": {
"k3": {
"k4": "v"
}
}
}
}
and a field list ["k1","k2","k3"], I need to retrieve the part {"k4": "v"}.
Below is my java7-style code:
// Ignore the map building code.
Map map1 = new HashMap();
Map map2 = new HashMap();
Map map3 = new HashMap();
Map map4 = new HashMap();
map4.put("k4", "v");
map3.put("k3", map4);
map2.put("k2", map3);
map1.put("k1", map2);
Map map = map1;
System.out.println(map); //=> {k1={k2={k3={k4=v}}}}
// Code to be transformed to java8 style
List<String> fields = Arrays.asList("k1", "k2", "k3");
for(String field: fields) {
map = (Map) map.get(field);
}
System.out.println(map); //=> {k4=v}
Then how to transform above code to java 8 stream style?
I don’t think that there is any benefit in converting this into a functional style; the loop is fine and precisely expresses what you are doing.
But for completeness, you can do it the following way:
map = (Map)fields.stream()
.<Function>map(key -> m -> ((Map)m).get(key))
.reduce(Function.identity(), Function::andThen).apply(map);
This converts each key to a function capable of doing a map lookup of that key, then composes them to a single function that is applied to you map. Postponing the operation to that point is necessary as functions are not allowed to modify local variables.
It’s also possible to fuse the map operation with the reduce operation, which allows to omit the explicit type (<Function>):
map = (Map)fields.parallelStream()
.reduce(Function.identity(), (f, key)->f.andThen(m->((Map)m).get(key)), Function::andThen)
.apply(map);
Maybe you recognize now, that this is a task for which a simple for loop is better suited.
How about?
fields.stream().reduce(map1, (m, key) -> (Map) m.get(key), (a, b) -> a);
So I have a struct and a dictionary that look like this:
struct minStruct {
var labelText:String?
var descText:String?
var imaginator:UIImage?
var rea:String?
var url:NSURL?}
var dict = [String:[minStruct]]()
Thus, I have a dictionary with the value as an array of structs. In my application I create an array of all the structs inside the dictionary to be able to show the structs in a tableView, which is done by this code:
let dictValues = Array(dict.values)
let dictFlat = Array(dictValues.flatten())
The new array dictFlat is used for populating the tableView, as it contains every struct that was contained inside of the original dictionary. If I would like to remove a struct from the tableView, i would of course remove it from the array dictFlat, however I need to remove the same struct from the original dictionary (dict) to achieve what I want. So my question is simply how to remove the same struct that is deleted from the array dictFlat from the dictionary dict. To clarify, you could you this example:
dict = ["Food":[minStruct(labelText: "this is a string", descText: "Also a string", imaginator: UIImage(named: "image-name")!, rea: "also a string", url: NSURL(string: "https://www.google.com")]]
Now dictFlat will contain the struct displayed inside of dict above, and now I want to delete that struct from both. Using swipe to delete from the tableView, the only struct that will be deleted is the one inside of dictFlat (using the indexPath to delete just as you would usually do when deleting from a tableView). Now I want to delete the same item which was deleted from dictFlat and also from the tableView, from the original dictionary (dict). So what I want is to check if dict contains the struct that was deleted from dictFlat, and if it does contain it, it shall be deleted.
I hope that I was clear enough, thanks in advance!
What is the trouble? See the example, I used there [Int] as a value, but it could be anything else
var dict:[String:[Int]] = [:]
let arr0 = [1,2,3,4,5]
let arr1 = [2,3,4,5,6]
dict["arr0"] = arr0
dict["arr1"] = arr1
// working copy
var arr = dict["arr0"] ?? []
// remove one value
arr.removeAtIndex(2)
// update your dictionary
dict["arr0"] = arr
print(dict) // ["arr1": [2, 3, 4, 5, 6], "arr0": [1, 2, 4, 5]]
In Java we could do the following
public class TempClass {
List<Integer> myList = null;
void doSomething() {
myList = new ArrayList<>();
myList.add(10);
myList.remove(10);
}
}
But if we rewrite it to Kotlin directly as below
class TempClass {
var myList: List<Int>? = null
fun doSomething() {
myList = ArrayList<Int>()
myList!!.add(10)
myList!!.remove(10)
}
}
I got the error of not finding add and remove function from my List
I work around casting it to ArrayList, but that is odd needing to cast it, while in Java casting is not required. And that defeats the purpose of having the abstract class List
class TempClass {
var myList: List<Int>? = null
fun doSomething() {
myList = ArrayList<Int>()
(myList!! as ArrayList).add(10)
(myList!! as ArrayList).remove(10)
}
}
Is there a way for me to use List but not needing to cast it, like what could be done in Java?
Unlike many languages, Kotlin distinguishes between mutable and immutable collections (lists, sets, maps, etc). Precise control over exactly when collections can be edited is useful for eliminating bugs, and for designing good APIs.
https://kotlinlang.org/docs/reference/collections.html
You'll need to use a MutableList list.
class TempClass {
var myList: MutableList<Int> = mutableListOf<Int>()
fun doSomething() {
// myList = ArrayList<Int>() // initializer is redundant
myList.add(10)
myList.remove(10)
}
}
MutableList<Int> = arrayListOf() should also work.
Defining a List collection in Kotlin in different ways:
Immutable variable with immutable (read only) list:
val users: List<User> = listOf( User("Tom", 32), User("John", 64) )
Immutable variable with mutable list:
val users: MutableList<User> = mutableListOf( User("Tom", 32), User("John", 64) )
or without initial value - empty list and without explicit variable type:
val users = mutableListOf<User>()
//or
val users = ArrayList<User>()
you can add items to list:
users.add(anohterUser) or
users += anotherUser (under the hood it's users.add(anohterUser))
Mutable variable with immutable list:
var users: List<User> = listOf( User("Tom", 32), User("John", 64) )
or without initial value - empty list and without explicit variable type:
var users = emptyList<User>()
NOTE: you can add* items to list:
users += anotherUser - *it creates new ArrayList and assigns it to users
Mutable variable with mutable list:
var users: MutableList<User> = mutableListOf( User("Tom", 32), User("John", 64) )
or without initial value - empty list and without explicit variable type:
var users = emptyList<User>().toMutableList()
//or
var users = ArrayList<User>()
NOTE: you can add items to list:
users.add(anohterUser)
but not using users += anotherUser
Error: Kotlin: Assignment operators ambiguity:
public operator fun Collection.plus(element: String): List defined in kotlin.collections
#InlineOnly public inline operator fun MutableCollection.plusAssign(element: String): Unit defined in kotlin.collections
see also:
https://kotlinlang.org/docs/reference/collections.html
Agree with all above answers of using MutableList but you can also add/remove from List and get a new list as below.
val newListWithElement = existingList + listOf(element)
val newListMinusElement = existingList - listOf(element)
Or
val newListWithElement = existingList.plus(element)
val newListMinusElement = existingList.minus(element)
Apparently, the default List of Kotlin is immutable.
To have a List that could change, one should use MutableList as below
class TempClass {
var myList: MutableList<Int>? = null
fun doSomething() {
myList = ArrayList<Int>()
myList!!.add(10)
myList!!.remove(10)
}
}
Updated
Nonetheless, it is not recommended to use MutableList unless for a list that you really want to change. Refers to https://hackernoon.com/read-only-collection-in-kotlin-leads-to-better-coding-40cdfa4c6359 for how Read-only collection provides better coding.
In Kotlin you must use MutableList or ArrayList.
Let's see how the methods of MutableList work:
var listNumbers: MutableList<Int> = mutableListOf(10, 15, 20)
// Result: 10, 15, 20
listNumbers.add(1000)
// Result: 10, 15, 20, 1000
listNumbers.add(1, 250)
// Result: 10, 250, 15, 20, 1000
listNumbers.removeAt(0)
// Result: 250, 15, 20, 1000
listNumbers.remove(20)
// Result: 250, 15, 1000
for (i in listNumbers) {
println(i)
}
Let's see how the methods of ArrayList work:
var arrayNumbers: ArrayList<Int> = arrayListOf(1, 2, 3, 4, 5)
// Result: 1, 2, 3, 4, 5
arrayNumbers.add(20)
// Result: 1, 2, 3, 4, 5, 20
arrayNumbers.remove(1)
// Result: 2, 3, 4, 5, 20
arrayNumbers.clear()
// Result: Empty
for (j in arrayNumbers) {
println(j)
}
UPDATE: As of Kotlin 1.3.70, the exact buildList function below is available in the standard library as an experimental function, along with its analogues buildSet and buildMap. See https://blog.jetbrains.com/kotlin/2020/03/kotlin-1-3-70-released/.
Confining Mutability to Builders
The top answers here correctly speak to the difference in Kotlin between read-only List (NOTE: it's read-only, not "immutable"), and MutableList.
In general, one should strive to use read-only lists, however, mutability is still often useful at construction time, especially when dealing with third-party libraries with non-functional interfaces. For cases in which alternate construction techniques are not available, such as using listOf directly, or applying a functional construct like fold or reduce, a simple "builder function" construct like the following nicely produces a read-only list from a temporary mutable one:
val readonlyList = mutableListOf<...>().apply {
// manipulate your list here using whatever logic you need
// the `apply` function sets `this` to the `MutableList`
add(foo1)
addAll(foos)
// etc.
}.toList()
and this can be nicely encapsulated into a re-usable inline utility function:
inline fun <T> buildList(block: MutableList<T>.() -> Unit) =
mutableListOf<T>().apply(block).toList()
which can be called like this:
val readonlyList = buildList<String> {
add("foo")
add("bar")
}
Now, all of the mutability is isolated to one block scope used for construction of the read-only list, and the rest of your code uses the read-only list that is output from the builder.
You can do with create new one like this.
var list1 = ArrayList<Int>()
var list2 = list1.toMutableList()
list2.add(item)
Now you can use list2, Thank you.
https://kotlinlang.org/docs/reference/collections.html
According to above link List<E> is immutable in Kotlin.
However this would work:
var list2 = ArrayList<String>()
list2.removeAt(1)
A list is immutable by Default, you can use ArrayList instead. like this :
val orders = arrayListOf<String>()
then you can add/delete items from this like below:
orders.add("Item 1")
orders.add("Item 2")
by default ArrayList is mutable so you can perform the operations on it.
In concept of immutable data, maybe this is a better way:
class TempClass {
val list: List<Int> by lazy {
listOf<Int>()
}
fun doSomething() {
list += 10
list -= 10
}
}
I'm writing an application in Flex / ActionScript and have a number of class member variables of type Array storing data.
My question is: what's the "best" way to clear out an Array object?
I noticed the ArrayCollection class has a function removeAll() which does this, but the basic Array class does not. Some possibilities I've considered are:
Iterating through the array, calling pop or shift on each element
Setting the array length to 0
Setting the member variable to a "new Array()" or "[]"
I'd say:
myArray = [ ];
That's explicit, short, and makes good use of the VM's garbage collector.
Your first alternative runs a lot of interpreted code to get the same result.
I don't know that the second does what you want; if it does, it's hacky, unclear.
The "new Array()" variant of the third alternative is just wordy, offering no advantage over an array literal. If you also write JS and use JSLint, you'll get yelled at for not using the array literal form.
I'm afraid to say but Warren Young is wrong when he said that setting the myArray = [] cause the garbage collector to pick up the array.
as you have the ability to add a reference to itself within itself, and therefore would never be collected and using up memory, especially if the array has some Sprites in the array, as they too would have the array references them and they too would never be collected.
Sly_cardinal and Richard Szalay are 100% correct. but the length parameter is not needed in Richard's.
To totally clear the array and make sure its collected by garbage then
myArray.splice(0);
myArray = null;
It depends on your context. While using Mr. Young's answer is often the most correct way to do things, it will not always work, especially if you have two variables pointing to the same array:
var foo:Array
var bar:Array
foo = bar = [ 1, 2, 3 ];
bar = [];
trace( foo ); // 1,2,3
On the other hand, if you actually empty the array manually:
var foo:Array
var bar:Array
foo = bar = [ 1, 2, 3 ];
var l:int = bar.length; // get the length FIRST!
// Otherwise bar.length will change
// while you iterate!
for( var i:int = 0; i < l; i++ )
{
bar.shift();
}
trace( foo ); // does not trace anything
If you can modify the array reference, then I would go with Warren's answer. If you need to modify the existing instance, you can also use Array.splice:
var arr : Array = [1, 2, 3, 4, 5];
arr.splice(0, arr.length);
According to this test the best way is to set length = 0