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.

case class Person(name: String, age: Int)

newPerson constructs a new person with the given name.

object Person {
  def newPerson(name: String): Person = {
    val p = Person(name, 42)
    p
  }
}

This syntax creates a new instance of the Person case class.

println(Person("Bob", 20))

You can name the fields when initializing an instance.

println(Person(name = "Alice", age = 30))

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.

val ann = Person(name = "Ann", age = 40)
println(ann)

It’s idiomatic to encapsulate new struct creation in constructor functions.

println(Person.newPerson("Jon"))

Access case class fields with a dot.

val s = Person(name = "Sean", age = 50)
println(s.name)

You can also use dots with struct pointers - the pointers are automatically dereferenced.

val sp = s
println(sp.age)

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.

val dog = new {
  val name: String = "Rex"
  val isGood: Boolean = true
}
println(dog)
$ scala hello-world.scala
Person(Bob,20)
Person(Alice,30)
Person(Ann,40)
Person(Jon,42)
Sean
50
{Rex,true}

Next example: Methods.