Search code examples
kotlinanonymous-class

Create instance of anonymous class in kotlin


In C# I can:

var a = new { prop42 = "42" };
Console.WriteLine("a.prop42 = " + a.prop42);

Or do some other things, like serialization anonymous class instances (for using in js in browser). No interfaces or abstract classes used, fully anonymous class instance.

It is possible to make same thing in Kotlin?


Solution

  • Yes, you can do the equivalent in Kotlin:

    val a = object { val prop42 = "42" }
    println("a.prop42 = ${a.prop42}")
    

    It's described in the language reference.  See also this question.

    This isn't often a good idea, though.  Because the type doesn't have a name, you can't use it in public declarations, such as class or top-level properties of that type; nor can you create lists or maps of it.  (In general, you can only refer to its named superclass — Any in this case, since you didn't specify one.)  So its use is a bit restricted.  (The lack of a name also makes the code harder to follow.)