This document discusses modeling products and categories in Scala using case classes. It describes the attributes of products (name, category, optional description) and categories (name, optional parent category). It shows how to define regular classes in Java and Scala to represent these, but notes that Scala case classes provide additional benefits out of the box, such as a companion object with factory methods, automatic fields from class parameters, nicer toString output, and attribute-based equality. It cautions that case classes have bytecode overhead and generated code that could clutter interfaces.
2. Let's
model
the
following
• A
product
has
a
name,
category
and
an
op;onal
descrip;on
• A
category
has
a
name
and
may
have
a
parent
category
• All
the
above
a>ributes
are
read-‐only
3. public class Category {
private String name;
private Category parent;
public Category(String name, Category parent) {
this.name = name;
this.parent = parent;
}
public String getName() {
return name;
}
public Category getParent() {
return parent;
}
}
4. public class Product {
private String name;
private String description;
private Category category;
// TODO: What am I missing?
public Product(String name, String description, Category category) {
this.name = name;
this.description = description;
this.category = category;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public Category getCategory() {
return category;
}
}
5. And
in
Scala?
class Category(
val name: String,
val parent: Option[Category])
class Product(
val name: String,
val description: String,
val category: Category)
6. Or
even
be>er,
case class Category(
name: String,
parent: Option[Category])
case class Product(
name: String,
description: String,
category: Category)
7. What
you
get
for
free
• Companion
object
with
factory-‐like
apply
methods
• Class
parameters
become
fields
• Nicer
toString
• A>ribute
based
equality
• Pa>ern
matching
• Copy
method
to
'clone'
instances
8. Be
mindful
of
• Bytecode
overhead
• Generated
code
might
clu>er
your
interface
• Case
class
inheritance