Structs in Scala
Based on your input, the target language is Scala. Below is the translation of the given code example into Scala.
Go’s structs are typed collections of fields. They’re useful for grouping data together to form records.
This person
class type has name
and age
fields.
newPerson
constructs a new person with the given name.
This syntax creates a new instance of the Person
case class.
You can name the fields when initializing an instance.
Omitted fields will give a compilation error as Scala case classes are immutable and don’t allow omitting fields without default values.
An &
prefix yields a pointer to the struct, in Scala, this is handled by getting the reference automatically.
It’s idiomatic to encapsulate new struct creation in constructor functions.
Access case class fields with a dot.
You can also use dots with struct pointers - the pointers are automatically dereferenced.
Structs are immutable by default in Scala. However, if you need mutability, you can use a mutable variable.
If a class type is only used for a single value, we don’t have to give it a name. The value can have an anonymous class type. This technique is commonly used for table-driven tests.
Next example: Methods.