Currently we can use anonymous objects only for local variables.
TypeScript allows anonymous objects on function parameters and returns, an I many time I wish Kotlin has that feature.
I think this concept is very similar to anonymous functions.
Before anonymous functions (Java), we have to create small interfaces.
Similarly, currently we have to create small classes to just return multiple values, or logically group parameters. Giving anonymous objects same power with anonymous functions will allow us to write more concise code.
fun foo(): Pair<String, Int> {
return "Hello" to 123
}
val (message, number) = foo()
Admittedly what you are suggesting has some subtle differences. In general I think Kotlin’s anonymous object and tuple syntax could be better. The C# team did a much better job, but they’re also not constrained by type erasure.
The main problem with anonymous types for these cases is the fact that it makes Java interoperability really hard. The additional argument would be that in many cases it is better codestyle to provide proper names for key elements of your API.
Another question is whether we actually want this to be supported in kotlin in the first place. I’m not sure anonymous types are the best way to go forward with kotlin but I don’t really have a strong opinion about this.
Also I can imagine that we might get something similar with multiple return values of java ever gets around to support value types (part of project valhalla I think) but that’s too far into the future to properly speculate about.
@spectre210 I think the closest we have to anonymous objects right now would be like this (the interface isn’t strictly necessary, but then you wouldn’t have x or s in scope without it…
interface Foo {
val x: Int
val s: String
}
fun foo(v: Foo) {
}
fun main() {
foo(object : Foo {
override val x: Int = 123
override val s: String = "Hello, world."
})
}