Polyglot CheatSheet - Struct / Data Class
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)
Define
C++: struct
A struct
is the same as a class
except that members in struct
s are default to public
, while members in class
es 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.
Python
namedtuple
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
dataclass
was added in 3.7
@dataclass
decorator and they are supposed to be "mutable namedtuples with default"
Scala
Scala provides case class
:
case class Field(
name: String,
count: Option[Long]
)
Create
Kotlin
val employee = Employee("10001", "Joe")
Rust
let mut emp1 = Employee {
id : 10001,
name : String::from("Joe"),
};