1

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?

Alex T
  • 2,067
  • 4
  • 20
  • 27
  • 3
    Does this answer your question? [How to create an instance of anonymous class of abstract class in Kotlin?](https://stackoverflow.com/questions/17516930/how-to-create-an-instance-of-anonymous-class-of-abstract-class-in-kotlin) - In this particular case, it seems like you could just use a Map object and a slightly different syntax. – CryptoFool Nov 07 '20 at 20:43
  • No, in that example created object - inheritor of some interface. So, this object must have only that fields, that defined in that interface. But I want to create properties that I want, I don't want to create interface here. In C# I can define any properties in anonymous class. – Alex T Nov 07 '20 at 20:49
  • I understand that I can use Map. But when I get data from map - types and keys names are not checked by compiler. So, it is not possible for now in Kotlin, right? – Alex T Nov 07 '20 at 20:53
  • Why do you think that "it must have only that fields, that defined in that interface"? You can define properties and methods in any anonymous class in Kotlin, https://kotlinlang.org/docs/reference/object-declarations.html#object-expressions – IR42 Nov 07 '20 at 20:55
  • Seems I'm write not fully correctly. Yes, I can define other fields. But I need to "implement" some interface. It is possible to instantiate instance without any interfaces? Like example in C#? – Alex T Nov 07 '20 at 21:00
  • `val a = object { val prop42 = "42" }` – IR42 Nov 07 '20 at 21:01
  • Seems you are right – Alex T Nov 07 '20 at 21:05
  • (Sorry, @IR42 — I wasn't copying your comments, honest!  Great minds think alike… :-) – gidds Nov 07 '20 at 21:06
  • @gidds haha, no problem, I was too lazy to write a detailed answer – IR42 Nov 07 '20 at 21:11
  • Thank you guys, sorry for my stupid questions :) – Alex T Nov 07 '20 at 21:14

1 Answers1

3

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.)

gidds
  • 16,558
  • 2
  • 19
  • 26