Kotlin's List missing "add", "remove", Map missing "put", etc? - collections

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
}
}

Related

Corda vault batch query by arbitrary indexed object property

looking for help regarding queries. if i'm looking for the latest LinearState of SomeObjectState by property someProp i can do the following:
private fun lookupBySomeProp(someProp: String) : List<StateAndRef<SomeObjectState>> {
val generalCriteria = VaultQueryCriteria(Vault.StateStatus.UNCONSUMED)
val somePropIdx = builder { SomePersistentObject::someProp.equal(someProp) }
val somePropQueryCriteria = VaultCustomQueryCriteria(somePropIdx)
val queryCriteria = generalCriteria.and(somePropQueryCriteria)
val results = serviceHub.vaultService.queryBy<SomeObjectState>(queryCriteria)
// ... handle results here
}
how would i go about doing a single batch lookup for multiple SomeObjectState objects given a list of someProp identifiers?
private fun lookupBySomeProps(somePropList: List<String>) : List<StateAndRef<SomeObjectState>> {
val generalCriteria = VaultQueryCriteria(Vault.StateStatus.UNCONSUMED)
// how do i build efficiently build my bulk query?
}
i'm expecting to have to do something along the lines of the following in order return multiple states matching the list but have been have trouble properly implementing it
val somePropeIdx = builder { SomePersistentObject::someProp.in(somePropList) }
From this link: https://docs.corda.net/api-vault-query.html you can use .in() in your criteria among many other things:
Binary logical (AND, OR)
Comparison (LESS_THAN, LESS_THAN_OR_EQUAL, GREATER_THAN, GREATER_THAN_OR_EQUAL)
Equality (EQUAL, NOT_EQUAL)
Likeness (LIKE, NOT_LIKE)
Nullability (IS_NULL, NOT_NULL)
Collection based (IN, NOT_IN)
Standard SQL-92 aggregate functions (SUM, AVG, MIN, MAX, COUNT)
The reason why your query in the question didn't work is because how Corda has defined the .in() function.
You had:
val somePropeIdx = builder { SomePersistentObject::someProp.in(somePropList) }
Substituting notIn works fine:
val somePropeIdx = builder { SomePersistentObject::someProp.notIn(somePropList) }
However, in order to use .in() you have to include backticks.
So your query would be:
val somePropeIdx = builder { SomePersistentObject::someProp.`in`(somePropList) }
You can see this difference in definition in the source here.

Functional way to accumulate within a Unit function in Kotlin?

I'm trying to force myself to employ functional programming in Kotlin, and wherever possible, avoid using mutable vars. Ordinarily, for an ad hoc test for a unit-returning function, I'd just println() something inside the function to see if it's working right. But for this test, I need to accumulate a string and then ultimately use assertEquals(...).
As usual, I found myself declaring a var in the enclosing scope and using += to accumulate into it. Is there a more functional way to do this by passing/chaining a function and eliminating the mutable var? Here's some simplified but illustrative code:
inline fun <T> Iterable<T>.forEachFrom(beg:Int, act:(T)->Unit) {
var i=0; if (beg>=0) for (e in this) if (i++ >= beg) act(e)
}
fun main(args:Array<String>) {
val l = listOf("zero", "one", "two", "three", "four")
// print-to-screen test
l.forEachFrom(2){print("$it-")}; println()
// output: two-three-four-
// accumulate-in-var test
var s = ""
l.forEachFrom(2){s += "$it-"}; println(s)
// output: two-three-four-
// Is there a purely functional way, without declaring a mutable var?
// val s = l.forEachFrom(2){accumulator???("$it-")}
// - OR -
// val s = l.forEachFrom(2).accumulator???("$it-")
// println(s)
}
A way to do the same with only kotlin-stdlib and retain the semantics of the code (i.e. iterate only once) is to convert the Iterable<T> to Sequence<T> and use the .drop(n) extension:
inline fun <T> Iterable<T>.forEachFrom(beg: Int, act: (T) -> Unit) =
if (beg >= 0)
asSequence().drop(beg).forEach(act) else
Unit
UPD: After discussing the overall question, we came up with another approach.
When you have a custom higher-order function that iterates over the items and only accepts a callback but does not return anything, you can wrap that custom iteration logic into a Sequence<T> by using buildSequence { ... } and passing yield(it) as the callback:
val sequenceFromCustomFunction = buildSequence {
l.forEachFrom(2) { yield(it) }
}
This allows you to work with this sequence in functional style and, in particular, fold the sequence:
val s = sequenceFromCustomFunction.fold("") { acc, it -> acc + it + "-" }

Kotlin invoke getter/setter reflectively

Beginner in Kotlin here.
I try to create and populate objects by reflection in a program. I cannot find the equivalent functionality in pure kotlin so my solution resembles the code below which works fine, but requires the use of dirty references like java.lang.String::class.java and intelliJ, understandably, doesn't seem to like this. Is there a simpler way that I am missing to do this?
val jclass = myObject::class.java
val setters = jclass.declaredMethods.filter { it.name.startsWith("set") }
for (s in setters) {
val paramType = s.parameterTypes.first()
val data = when(paramType) {
java.lang.Integer::class.java -> foo
java.lang.Double::class.java -> bar
java.lang.String::class.java -> baz
}
s.invoke(myObject, data)
}
You can use Kotlin reflection, which requires you to add kotlin-reflect as a dependency to your project.
Here you can find kotlin-reflect for Kotlin 1.0.5, or pick another version if you use different Kotlin version.
After that, you can rewrite your code as follows:
val properties = myObject.javaClass.kotlin.memberProperties
for (p in properties.filterIsInstance<KMutableProperty<*>>()) {
val data = when (p.returnType.javaType) {
Int::class.javaPrimitiveType,
Int::class.javaObjectType -> foo
Double::class.javaPrimitiveType,
Double::class.javaObjectType -> bar
String::class.java -> baz
else -> null
}
if (data != null)
p.setter.call(myObject, data)
}
Some details:
Despite using Kotlin reflection, this approach works with Java classes as well, their fields and accessors will be seen as properties, as described here.
Just like with Java reflection, memberProperties returns public properties of this type and all its supertypes. To get all the properties declared in the type (including the private ones, but not those from the supertypes), use declaredMemberProperties instead.
.filterIsInstance<KMutableProperty<*> returns only the mutable properties, so that you can use their p.setter later. If you need to iterate over the getters of all the properties, remove it.
In the when block, I compared p.returnType.javaType to Int::class.javaPrimitiveType and Int::class.javaObjectType, because what's Int in Kotlin can be mapped to either Java int or java.lang.Integer depending on its usage. In Kotlin 1.1, it will be enough to check p.returnType.classifier == Int::class.
If You need to get property getter/setter, there is a couple of built-in constructions for it YourClass::propertyName
have a look at example bellow
fun main(args: Array<String>) {
val myObject = Cat("Tom", 3, 35)
println(Cat::age.getter.call(myObject)) // will print 3
Cat::age.setter.call(myObject, 45)
print(myObject) // will print Cat(name=Tom, age=45, height=35)
}
data class Cat(var name : String, var age : Int, val height : Int)
but sometimes you don't know class exactly(working with generics) or need to get list of properties, then use val <T : Any> KClass<T>.declaredMemberProperties: Collection<KProperty1<T, *>> it will return all properties, some of them can be mutable(var) and some immutable(val), you can find out immutability by checking belonging to KMutableProperty<*> (by filtering with is operator or using convenience methods such as filterIsInstance<KMutableProperty<*>>)
about your code snippet
I absolutely agree with hotkey, but now it is better to use myObject::class.declaredMemberProperties instead of myObject.javaClass.kotlin.memberProperties
because the second one is deprecated
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.jvm/java-class.html
data class Cat(var name : String, var age : Int, val height : Int)
#JvmStatic
fun main(args: Array<String>) {
val myObject = Cat("Tom", 3, 35)
val properties = myObject::class.declaredMemberProperties
for (p in properties.filterIsInstance<KMutableProperty<*>>()) {
val data = when (p.returnType.javaType) {
Int::class.javaPrimitiveType,
Int::class.javaObjectType -> 5
String::class.java -> "Rob"
else -> null
}
if (data != null)
p.setter.call(myObject, data)
}
println(myObject)
// it will print Cat(name=Rob, age=5, height=35),
// because height isn't var(immutable)
}
in general, I would approach similar problems with such construction in mind
val myObject = Cat("Tom", 3, 35)
Cat::class.declaredMemberProperties
//if we want only public ones
.filter{ it.visibility == KVisibility.PUBLIC }
// We only want strings
.filter{ it.returnType.isSubtypeOf(String::class.starProjectedType) }
.filterIsInstance<KMutableProperty<*>>()
.forEach { prop ->
prop.setter.call(myObject, "Rob")
}
println(myObject)
//it will print Cat(name=Rob, age=3, height=35),
//because name is only eligible in this case

immutablejs with modifiable nested properties yay or nay?

In the following I'm able to edit the property map of dungeon which is immutablejs Record type. If immutablejs doesn't immune deeper nested objs from being changed, is there a point at all in defining a structure such as the following?
const DungeonObj = Immutable.Record({
map : [1,2,3]
});
class Dungeon {
static someFunc(map) {
map[0] = 'changed';
return map;
}
}
let dungeon = new DungeonObj();
console.log(Dungeon.someFunc(dungeon.map));
console.log(dungeon.map);
This will print:
["changed", 2, 3]
["changed", 2, 3]
Should I have defined map as a List instead? Does it makes sense to have deep nested immutable data types say a Record inside a List inside a Map?

Is it possible to have a dictionary with a mutable array as the value in Swift

I am trying to do this:
var dictArray = [String:[String]]()
dictArray["test"] = [String]()
dictArray["test"]! += "hello"
But I am getting the weird error NSString is not a subtype of 'DictionaryIndex<String, [(String)]>'.
I just want to be able to add objects to an array inside a dictionary.
Update: Looks like Apple considers this a "known issue" in Swift, implying it will work as expected eventually. From the Xcode 6 Beta 4 release notes:
...Similarly, you cannot modify the underlying value of a mutable
optional value, either conditionally or within a force-unwrap:
tableView.sortDescriptors! += NSSortDescriptor(key: "creditName", ascending: true)
Workaround: Test the optional value explicitly and then assign the
result back:
if let window = NSApplication.sharedApplication.mainWindow {
window.title = "Currently experiencing problems"
}
tableView.sortDescriptors = tableView.sortDescriptors!
You can only do this
var dictArray = [String:[String]]()
dictArray["test"] = [String]()
var arr = dictArray["test"]!;
arr += "hello"
dictArray["test"] = arr
because dictArray["test"] give you Optional<[String]> which is immutable
6> var test : [String]? = [String]()
test: [String]? = 0 values
7> test += "hello"
<REPL>:7:1: error: '[String]?' is not identical to 'UInt8'
append also won't work due to the same reason, Optional is immutable
3> dictArray["test"]!.append("hello")
<REPL>:3:18: error: '(String, [(String)])' does not have a member named 'append'
dictArray["test"]!.append("hello")
^ ~~~~~~
BTW the error message is horrible...
You may use NSMutableArray instead of [String] as a value type for your dictionary:
var dictArray: [String: NSMutableArray] = [:]
dictArray["test"] = NSMutableArray()
dictArray["test"]!.addObject("hello")
This is still an issue in Swift 3. At least I was able to create method that can handle it for you.
func appendOrCreate(newValue: Any, toArrayAt key: String, in existingDictionary: inout [AnyHashable:Any]) {
var mutableArray = [Any]()
if let array = existingDictionary[key] as? [Any]{
//include existing values in mutableArray before adding new value
for existingValue in array {
mutableArray.append(existingValue)
}
}
//append new value
mutableArray.append(newValue)
//save updated array in original dictionary
existingDictionary[key] = mutableArray
}
The problem is that we want class semantics here but have to use structs. If you put class objects into the dictionary, you get what you want!
So, if you haveĀ¹ to have mutable values, you can wrap them in a class and perform updates with a closure:
class MutableWrapper<T> {
var rawValue: T
init(_ val: T) {
self.rawValue = val
}
func update(_ with: (inout T) -> Void) {
with(&self.rawValue)
}
}
Example:
func foo() {
var dict = [String: MutableWrapper<[String]>]()
dict["bar"] = MutableWrapper(["rum"])
dict["bar"]?.update({$0.append("gin")})
print(dict["bar"]!.rawValue)
// > ["rum", "gin"]
}
For what it's worth, I do not see a way to keep caller and wrapper in sync. Even if we declare init(_ val: inout T) we will end up with a copy in rawValue.
Performance is not necessarily an issue since the compiler optimizes structs heavily. I'd benchmark any mutable solution against what looks like lots of copy-updates in the code.
Since Swift 4.1 you can provide a default value to the subscript which allows you to solve this quite naturally now:
dictArray["test", default: []].append("hello")

Resources