See: Can I specify a meaningful name for an anonymous class in C#?
In C# you can write:
var e = new { ID = 5, Name= "Prashant" };
assertEquals( 5, e.ID )
But in Scala I end up writing:
var e = (5, "Prashant")
assertEquals( 5, e._1 )
Scala maintains type safety through the use of generics (as does C#), but loses the readability of the name of each field, e.g I use “_1” instead of “ID”.
Is there anything like this in Scala?
Ok, let’s make stuff clear. This does use reflection on Scala 2.7 and Scala 2.8, because the type of
eis, in this case, a structural type, which Scala handles through reflection. Here is the generated code, at clean-up time (scalac -Xprint:cleanup):There is some caching going on, but if I alternated between
idandnameit would invalidate the cache already. Scala 2.8 also does reflection, and also caches, but it uses a more efficient caching technique, which should provide better overall performance. For reference, here is the clean-up of Scala 2.8: