Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Scala Cookbook

Practical, copy-paste-ready recipes for Scala code generation. For the full API of each spec type, see Building Functions & Fields, Building Types & Enums, and Files & Projects.

Case class

extern crate sigil_stitch;
use sigil_stitch::prelude::*;
fn main() {
let type_spec = TypeSpec::builder("User", TypeKind::Struct)
    .doc("A user case class.")
    .add_primary_constructor_param(
        ParameterSpec::new("name", TypeName::primitive("String")).unwrap(),
    )
    .add_primary_constructor_param(
        ParameterSpec::new("age", TypeName::primitive("Int")).unwrap(),
    )
    .add_primary_constructor_param(
        ParameterSpec::new("email", TypeName::primitive("String")).unwrap(),
    )
    .build()
    .unwrap();
}
/**
 * A user case class.
 */
case class User(name: String, age: Int, email: String) {
}

Trait with type parameter

extern crate sigil_stitch;
use sigil_stitch::prelude::*;
fn main() {
let type_spec = TypeSpec::builder("Repository", TypeKind::Trait)
    .add_generic_param(GenericParamSpec::single("T").unwrap())
    .doc("Generic data repository.")
    .add_method(
        FunSpec::builder("findById")
            .returns(vec![TypeName::primitive("Option[T]")])
            .add_param(ParameterSpec::new("id", TypeName::primitive("String")).unwrap())
            .build()
            .unwrap(),
    )
    .add_method(
        FunSpec::builder("save")
            .add_param(ParameterSpec::new("entity", TypeName::primitive("T")).unwrap())
            .build()
            .unwrap(),
    )
    .build()
    .unwrap();
}
/**
 * Generic data repository.
 */
trait Repository[T] {
  def findById(id: String): Option[T]

  def save(entity: T)
}

Enum

extern crate sigil_stitch;
use sigil_stitch::prelude::*;
use sigil_stitch::spec::enum_variant_spec::EnumVariantSpec;
fn main() {
let type_spec = TypeSpec::builder("Color", TypeKind::Enum)
    .doc("Supported colors.")
    .add_variant(EnumVariantSpec::new("Red").unwrap())
    .add_variant(EnumVariantSpec::new("Green").unwrap())
    .add_variant(EnumVariantSpec::new("Blue").unwrap())
    .build()
    .unwrap();
}
/**
 * Supported colors.
 */
enum Color {
  Red,
  Green,
  Blue
}

Bounded type parameter

extern crate sigil_stitch;
use sigil_stitch::prelude::*;
fn main() {
let body = CodeBlock::of("if (a.compareTo(b) >= 0) a else b", ()).unwrap();

let fun = FunSpec::builder("max")
    .add_generic_param(
        GenericParamSpec::single("T").unwrap().with_bound(TypeName::primitive("Comparable[T]")).unwrap(),
    )
    .returns(vec![TypeName::primitive("T")])
    .add_param(ParameterSpec::new("a", TypeName::primitive("T")).unwrap())
    .add_param(ParameterSpec::new("b", TypeName::primitive("T")).unwrap())
    .body(body)
    .build()
    .unwrap();
}
def max[T <: Comparable[T]](a: T, b: T): T = {
  if (a.compareTo(b) >= 0) a else b
}

Newtype

extern crate sigil_stitch;
use sigil_stitch::prelude::*;
fn main() {
let type_spec = TypeSpec::builder("Meters", TypeKind::Newtype)
    .extends(TypeName::primitive("Double"))
    .build()
    .unwrap();
}
class Meters(val value: Double)

Integer literal types

Use the shared integer-singleton leaf and ordinary union composition:

extern crate sigil_stitch;
use sigil_stitch::prelude::*;
fn main() -> Result<(), SigilStitchError> {
let file = FileSpec::builder_with("Status.scala", sigil_stitch::lang::scala::Scala::new())
    .add_type(
        TypeSpec::builder("Status", TypeKind::TypeAlias)
            .extends(TypeName::union(vec![
                TypeName::integer_literal("200"),
                TypeName::integer_literal("201"),
            ]))
            .build()?,
    )
    .add_type(
        TypeSpec::builder("Large", TypeKind::TypeAlias)
            .extends(TypeName::integer_literal("2147483648"))
            .build()?,
    )
    .build()?;
let output = file.render(80)?;
assert!(output.contains("type Status = 200 | 201"));
assert!(output.contains("type Large = 2147483648L"));
Ok(())
}
type Status = 200 | 201
type Large = 2147483648L

Values in the signed Int range use unsuffixed syntax; larger magnitudes use Long singleton syntax through the signed Long boundaries. Inputs remain canonical decimal text without an L suffix. Values outside the native range return UnsupportedTypeName, not a primitive or BigInt fallback. See integer literal types for the shared validation and exact-value contract.