Polyglot CheatSheet - Struct / Data Class

Updated: 2021-11-19

Simple classes that are used for storing data. It may be called struct, or data class, or case class, or record, depending on the language.

Struct vs tuple: Struct is similar to a tuple, but it needs a name to the data structure and a name for its fields. Differently from the tuple we don’t need to follow any order of the fields. (struct = named tuple)


C++: struct

A struct is the same as a class except that members in structs are default to public, while members in classes default to private.

Rust: struct

struct Employee {
   id: i32,
   name: String,

Java: record

Introduced in Java 14.

public record Employee {
  int id,
  String name
} {}

Kotlin: data class

data class Employee(var id: String, var name: String)

Constructor, toString(), equals(), hashCode(), and additional copy() and componentN() functions are generated automatically.



namedtuple is immutable

>>> Node = namedtuple('Node', 'val left right')
>>> Node = namedtuple('Node', ['val','left','right'])

>>> Node.__new__.__defaults__ = 0, None, None
>>> Node()
Node(val=0, left=None, right=None)


dataclass was added in 3.7

@dataclass decorator and they are supposed to be "mutable namedtuples with default"


Scala provides case class:

case class Field(
    name: String,
    count: Option[Long]



val employee = Employee("10001", "Joe")


let mut emp1 = Employee {
  id : 10001,
  name : String::from("Joe"),