Spread-object operator missing in kotlin?


#1

I was wondering if there is something like the spread-object operator found in Javascript/Typescript? I am aware that there is a spread function arguments operator.

The spread object operator allows one to pass-on attribute values of objects of shared types without constructors. And thus, avoiding to list out all attributes of an object one-by-one again and again.

For example,

var defaultVehicleOverrides = { wheels: 4, seats: 5 }
var myCar = { ...carFromDb, ...defaultVehicleOverrides }

#2

I’m not sure if this is what you’re looking for, but you can spread a collection with *:

fun foo(vararg numbers: Int) {
    numbers.forEach(::println)
}

val list = listOf(1, 2, 3)

foo(*list.toIntArray())

#3

Thanks. I know there is a spread operator for lists/arrays. But how about object properties. For example in latest javascript versions (or typescript),

var myContact = { name: 'Abe', email: 'abe@email.com' }
var oldPerson = { age: 50 }
var myPerson = { ...myContact, ...oldPerson}
// Now myPerson will be { name: 'Abe', email: 'abe@email.com', age: 50 }

#4

Imagine this

class Contact(val name: String, val email: String)
class Person(val age: Int)
val contact = Contact("Abe", "abe@email.com")
val person = Person(50)
val merged = ...do something with variables 'contact' and 'person'...

Now, what type of variable merged would be?


#5

In my specific use-case, Person class would be derived from Contact. That is a person is a special type of contact. The code would be:

class Person(name: String, email: String, val age: Int): Contact (name, email)

A useful scenario would be if I would like to provide override values for all contacts for some operation. For example, for drawPeople() the signature could be:

fn drawPeople(people: Array<Person>, contactOverride: Contact) {
    people.forEach {
        // A hypothetical spread object operator:
        drawContact({ ...it, ...contactOverride })
    }
}

#6

Kotlin is a fundamentally different language than javascript. However, if you expose those data types as maps. then you can just use the plus operator on both maps and get a combined map. Of course if you have specific types rather than generic maps you can make your own combinators, but you’ll have to write that yourself. There is no way that that would happen automatically.


#7

This sounds like dataarg which was one of the proposed features in last year’s survey, item 20 on the list.

I quite like the idea myself but unfortunately it finished last (of 20) when the votes were counted so I’ll be surprised if it’s added to the language anytime soon.