Using anonymous objects as parameters and return types

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.

example:

fun demo(param: (string:String, int: Int))) : (list: List, string: String) {
return object { list: listOf(param.string), string: param.int.toString() }
}

fun main() {
val r = demo(object { string: “demo”, int: 10 })
println(r.string)
}

It looks similar to Kotlin’s tuple syntax:

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.

This is bad practice in a statically typed language. Having said that, if you are targeting JavaScript then you can use the dynamic type.

Why would that be bad practice? I don’t see anything in the OPs example that can’t be inferred statically?

You are right. I didn’t parse the example code because it was not formatted. My bad.

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.

1 Like

What you want are anonymous (structural) types where constructors aren’t necessary:

fun foo(x:class{x:Int,s:String}){...}
val r=foo(object{s:"hello",i:2})

This isn’t yet supported in Kotlin, and the question is if it ever will be because of Java interoperability.

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."
    })
} 
1 Like