(Assignment expressions) Kotlin Syntax

What do you think about to have this syntax on Kotlin

Person is an object with attribut name like this data class Person(val name: String)

val personOne → a non null person

val name = val personTwo.name = personOne

personOne is assign to personTwo and personTwo.name is assign to name, for check after some validation on name…

1 Like

Welcome to the forum!

Hmm, so would the line
val name = val personTwo.name = personOne
not only assign personTwo’s name but also declare personTwo? Alternative it could be that personTwo is already declared outside of your example.

This is pretty close to assignment expressions. Which would enable code like a = b = c. Personally I think assignment expressions don’t provide enough benefit to be a high priority addition–so the minus 100 point rule pushes it out for me.

You do save an extra line of code, but IMO that hurts the readability in a lot of cases, and in the cases it does help, there are pretty good alternatives.

One of the common examples for assignment expressions is helping with loops. For example in Java you’ll see,
while ((input = readSomeInput()) != null) { //... }

There’s been previous discussion on assignment expressions already–you should be able to find some by searching on the forum (I would link it but I’m on mobile atm).

1 Like

Simple assignment expressions are one thing and I’m not sure it’s something kotlin really needs.
But this syntax as described above goes even further and while it looks like a powerful way to do assignments it’s really hard to understand for a reader especially if the class definitions aren’t right next to the code.

val name = process.company.ceo.name = queryResultDto.company = someFunctionCall()

I guess that would be leagal. E.g someFunCall could return a QueryResultDto or a Company. Then queryResultDto.company would be assigned to process.company and after that process.company.ceo.name would be assigned to name. Unless you know all types and subtypes any property in the “expression” process.company.ceo.name could be set here. This get even worse if you consider polymorphism or generics not to mention classes that have references to objects of the same type.
While it looks like a cool idea it would probably cause lots of problems and not really solve any existing problems. Sure code would be a bit shorter but at what price?

3 Likes