The Scala target-language layer for Skmtc generators (@skmtc/lang-scala). It covers the projection base factories, ScalaSnippet, the register shape with package imports, the six identifier kinds, one folder as one package, the head and value render model, methods as members of a class, Option for absent values, comments with @param lines, and the producers for case classes, enums, objects, methods and names. Use ALONGSIDE skmtc-generator whenever a generator writes Scala.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Skmtc Lang Scala?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/skmtc-skmtc-lang-scala)
---
name: skmtc-lang-scala
version: 0.1.0
description: >
The Scala target-language layer for Skmtc generators (@skmtc/lang-scala).
It covers the projection base factories, ScalaSnippet, the register
shape with package imports, the six identifier kinds, one folder as one
package, the head and value render model, methods as members of a
class, Option for absent values, comments with @param lines, and the
producers for case classes, enums, objects, methods and names. Use
ALONGSIDE skmtc-generator whenever a generator writes Scala.
metadata:
internal: true
---
# The Scala layer (@skmtc/lang-scala)
Read `skmtc-generator` first. The two worked examples are
`@skmtc/gen-scala-circe` (a model generator) and `@skmtc/gen-scala-sttp`
(an SDK: an Index for each service, and an accumulator for the client).
Generated code targets Scala 3.3 or later. The style of both follows
`softwaremill/sttp-ai`: see "The reference SDK" at the end.
## 1. Declare the language
The import graph declares the language. `src/base.ts` imports a factory,
and each snippet extends `ScalaSnippet`. Import each module by its own
path, never the root of the package.
```ts fragment
import { ScalaName } from '@skmtc/lang-scala/ScalaName'
import { toScalaModelProjectionBase } from '@skmtc/lang-scala/toScalaModelProjectionBase'
export const ScalaCirceBase = toScalaModelProjectionBase<EnrichmentSchema>({
id: denoJson.name,
toIdentifierName({ ref }) {
return toTypeName(new ScalaName(toModelName(ref)).toType())
},
toIdentifierType,
toExportPath({ ref, enrichments, variant }) {
const name = this.toIdentifierName({ ref, enrichments, variant })
return `@/${name}.scala`
},
})
```
The factories are `toScalaModelProjectionBase`,
`toScalaOasOperationProjectionBase` and `toScalaOasOperationIndexBase`.
## 2. A folder is a package
Every file of one folder is one Scala package. A file reads a name of
its own package with no import.
- **Put every generated file in one folder.** The engine registers an
import for a definition in another file. For a file in the same
folder, `ScalaFile` renders nothing. For a file in another folder, it
renders an import of the other package.
- **Each name is in the whole package.** Two files cannot each declare
`Response`. The generated files and the hand-written files of the
package read some names with no package. A model with such a name gets
another name (`reservedNames` in `gen-scala-circe/src/base.ts`).
- **The `package` line comes from the folders.** `'@/'` is the project's
`basePath`. The packages start below the last folder of `basePath`
with the name `scala` or `scala-…`: `./src/main/scala/com/acme/petstore`
gives `package com.acme.petstore`. With no such folder, the last folder
of `basePath` is the first part of the package. With no `basePath`,
it is `api`. Each folder below `'@/'` adds a part: with no `basePath`,
`'@/models/Pet.scala'` gives `package api.models`.
`toPackageName(path, settings)` gives the name.
- **Two files of the package can declare one name, and the engine does
not see it.** A file knows its own definitions only. The compiler
reports a name that two files declare, so the layer does not look for
it.
## 3. Register
| Caller | Call | File |
|---|---|---|
| Projection | `this.register(args)` | Its own export file |
| Projection | `this.registerInto(path, args)` | The file you name |
| Snippet | `this.register({ ...args, destinationPath })` | The file you name |
`args` is `{ imports?, definitions?, custom? }`. There is no `reExports`.
- An import is the names that a file reads from one package:
`imports: { 'io.circe': ['Decoder', 'Encoder'], 'io.circe.syntax': ['*'] }`.
The file renders one line for each package, sorted:
`import io.circe.{Decoder, Encoder}`.
- The producer that writes a name registers its import, in its
constructor. A producer that no code builds registers nothing.
- With no `custom`, a file starts with
`// Generated by Skmtc. Do not edit.`.
- The engine adds the suffix of generated files to the export path of a
projection. It writes a `destinationPath` with no change. An
accumulator registers its file by path. For such a file,
`toGeneratedPath(context, '@/Services.scala')` gives the path with
the suffix.
## 4. Identifier kinds
| Kind | Factory | Renders |
|---|---|---|
| `caseClass` | `createCaseClass(name)` | `final case class Pet` + value |
| `enum` | `createEnum(name)` | `enum PetStatus` + value |
| `type` | `createType(name)` | `type Tags = ` + value |
| `class` | `createClass(name)` | `final class PetsService` + value |
| `trait` | `createTrait(name)` | `trait Services` + value |
| `def` | `createDef(name)` | `def getApiPets` + value |
- A `type` is a second name of one type. It has the `given` values of
that type, so an alias of `List[String]` has its codecs.
- The kind does not change an import: Scala imports each of them by
name.
- A name is public unless it says otherwise. An identifier with
`exported: false` starts with `private`.
## 5. Head and value
The identifier renders the head of a declaration, and the value renders
all that follows. The value of a `caseClass` is a `ScalaCaseClass` and
its companion, and the value of a `def` is a `ScalaMethod`. A projection
holds one and renders it.
**A comment is above its declaration**, where the value cannot write
it. A definition reads the `doc` field of its value, which is a
`ScalaDoc`:
```ts fragment
export class ServiceMethod extends ServiceMethodBase {
doc: ScalaDoc
value: ScalaMethod
…
this.doc = new ScalaDoc({ description: new MethodSummary(operation), params: inputs })
}
```
- `description` is a string or a producer. A producer renders with the
file, so no constructor renders text.
- `params` is one `{ name, description }` for each field or parameter.
Each is a `@param` line of the comment of the declaration, where
Scaladoc reads it. The comment has no line for one with no
description. A comment with no text renders nothing.
- `ScalaDoc` writes `/*` and `*/` of a description with the HTML code of
the slash. A comment of Scala can hold another comment.
## 6. A method is a member of a class
Scala declares a method in the body of its class, one level deeper. An
Index is the class, and its members are the methods:
```ts fragment
this.value = new ScalaClass({
parameters: [new ScalaParameter({ name: CLIENT, type: CLIENT_NAME })],
members: this.definitions,
})
```
Give `ScalaClass` the `definitions` array of the Index itself: the
methods arrive after the constructor, and the class reads the array when
it renders. A member projection states `toIndex: () => TheIndex` and no
`toExportPath`. The Index accepts `def` definitions only. Any other
definition in its file is a declaration of the file, below the class.
## 7. Option
Scala has no `null` in its own types. A value that can be absent or
`null` is an `Option`, and `None` is the absent value.
- `ScalaOption({ type, optional })` writes `Option[T]`, or `T`.
- `ScalaParameter({ name, type, required })` writes the default `None`
for a field or a parameter with `required: false`:
`limit: Option[Long] = None`. A required value that can be `null` is
an `Option` with no default.
- `ScalaParameter({ name, type, defaultValue })` writes the default that
you give: `kind: Kind = Kind.Cat`.
- A case class can hold itself, so a reference inside a cycle has the
same form as any other.
- Decide the `Option` in one class (`ScalaCirceOptional` in
`gen-scala-circe`).
## 8. Indentation
Scala 3 reads the indentation of a line as the block it belongs to. A
producer renders its own lines from column 0. `ScalaIndented` is the
only code that writes the two spaces of a level, so blocks nest to any
depth: `new ScalaIndented(content, { levels: 2 })`. Do not write the
indentation of a nested producer in a template.
A producer does not wrap or align. A project runs `scalafmt` after
generation.
## 9. Producers
| Producer | Renders |
|---|---|
| `ScalaList.toArguments(items)`, `.toParameters`, `.toLines`, `.toParagraphs` | `a, b`, one item on each line with a comma, one item on each line, a blank line between items |
| `ScalaIndented(content, { levels? })` | The content some levels deeper |
| `ScalaCaseClass(fields)` | `(`, a field on each line, `)` |
| `ScalaParameter({ name, type, required?, defaultValue?, member? })` | `petId: Long`, `limit: Option[Long] = None`, `kind: Kind = Kind.Cat`, `val value: String` |
| `ScalaEnum({ parameters, cases })`, `ScalaEnumCase({ name, parent, arguments })` | `(val value: String):` and `case Sold extends PetStatus("sold")` |
| `ScalaObject({ name, members })` | `object Pet:` and its members. With the name of a class of the file, it is the companion |
| `ScalaClass({ parameters, members })` | `(client: Client):` and each member |
| `ScalaTrait({ selfType?, members })` | `:`, `this: Client =>` and each member |
| `ScalaMembers(members)` | The members one level deeper, with a blank line between |
| `ScalaMethod({ parameters, result, body })` | `( … ): Result =` and the body |
| `ScalaChain({ receiver, calls })` | A value, and a call on each line below it |
| `ScalaGeneric({ name, arguments })` | `List[Pet]`, `Map[String, Json]` |
| `ScalaQualified({ qualifier, name })` | `Order.ShipTo` |
| `ScalaOption({ type, optional })` | `Option[String]`, or `String` |
| `ScalaDoc({ description?, params? })` | A comment with `@param` lines, or nothing |
An item that is `undefined` or `null` is absent. `ScalaClass`,
`ScalaTrait` and `ScalaMembers` read their array when they render.
## 10. Names and literals
- `new ScalaName(text).toType()` for a class, an enum, a case and a type
alias: `pet_id` gives `PetId`. `.toTerm()` for a field, a parameter
and a value: `petId`. Each form is a valid Scala name for any text. A
text with no letter and no digit gives `X` and `x`.
- `toTerm()` writes a keyword in backticks, as Scala code does
(`` `type` ``). A name that starts with a digit is in backticks too
(`` `2fa` ``).
- Lower-case letters after a digit stay in the word of the digit.
`2nd line` gives `` `2ndLine` ``, and `v2beta` gives `v2beta`.
- Every case class has some members (`notify`, `toString`). A name of
such a member gets the word `Value`: backticks do not help there.
- `new ScalaNameScope(reserved).claim(name)` makes the names of one list
unique. A list is the fields of a case class, the cases of an enum, or
the parameters of a method. Two keys can give one Scala name
(`user-id` and `user_id`), and the second gets a number. Put the names
that the code around the list reads in `reserved`.
- `scalaTypes` has the names of the types that code writes with no
import: `scalaTypes.string`, `scalaTypes.unit`, `scalaTypes.list`.
- `toStringLiteral(value)` writes a string of the document as a Scala
string. Use it for each key, path and enum value.
## 11. A declaration and a type position differ
An object with properties is a case class in its declaration, and only a
name in a type position. A string with values is an enum in its
declaration, and only a name in a type position. A union with a
discriminator is an enum of the same two forms. The router contract has
no argument for the position. `gen-scala-circe` solves this as follows:
- `toScalaCirceValue(place)` returns the router for one place. A
`ScalaCircePlace` has three fields. `scope` declares a type that the
schema needs. `name` is the name of that type. `declares` is the kind
of the declaration that has the schema as its value. In a type
position, `declares` is absent.
- In a type position, an inline object or an inline enum declares its
type in the scope. It renders the name that the scope gives.
- A case of a union has the name of its model (`Pet.Cat`). Inside the
enum that name is the case. Thus the type of its value has the package
before it: `case Cat(value: orders.Cat)`. `toPackageName` gives the
package of the file of the model.
- **The scope of a property is the companion of its class**
(`CompanionScope`). The type of the inline property `ship_to` of
`Order` is `Order.ShipTo`. No component can have that name, so an
inline type never clashes with a component. Two classes can each have
a `ShipTo`. The companion declares the type after its codecs. The type
of an inline property of `ShipTo` is in the companion of `ShipTo`.
- **The scope of a schema that no class holds is its file**
(`FileScope`). Such a schema is the items of a type alias. The body,
the response and a parameter of an operation are too. The name comes from
the definition that uses the type: `BatchesItem`,
`CreateApiOrdersBody`.
- An array passes the place on with `Item` after the name, and a map
with `Value`.
- `toIdentifierType` gives the kind of the definition. The lint rule
`skmtc/single-dispatch` allows a test of `schema.type` there.
- A generator can write types of its own (the parameters of a method).
It calls `toScalaCirceValue` with a `FileScope` of its own file.
A model projection of this shape declares no `schemaToValueFn` and no
`createIdentifier`: an inline schema needs a scope, which
`insertNormalizedModel` does not pass.
## 12. Pitfalls
| Symptom | Fix |
|---|---|
| `Not found: type Json` | The producer that writes `Json` did not register `'io.circe'` |
| `X is already defined as class X` | Two files of the package declare one name. Give one of them another name in `base.ts` |
| `Generated class X differs only in case from Y` | Two components give names that differ only in case (`imagedata` and `ImageData`). Give one of them another name in the document or with an overlay, or change `toIdentifierName` in a clone |
| `… does not take type parameters`, in every file | A model has the name of a type that the files read with no package (`Either`, `Option`). Add the name to `reservedNames` |
| `value values is not a member of …` | A case of an enum has the name of the enum, and hides it in the companion. Put the name of the enum in the `ScalaNameScope` of its cases |
| A type in a companion is read in place of a model | An inline type of a class has the name of a model that the same class refers to (`Order.Address` and `Address`). Move the inline schema to `components.schemas`, or change `toPropertyTypeName` in a clone |
| `type Cat is not a member of <root>` | The files are in no package, and a case of a union cannot name its model there. Add a folder below `scala` to `basePath` |
| A class renders with no methods | `ScalaClass` got a copy of `definitions`. Give it the array itself |
| A body is one level too shallow, and the compiler reads it as another block | The template wrote the indentation. Wrap the nested producer in `ScalaIndented` |
| A comment before a field does not show in the documentation | Scaladoc reads `@param` in the comment of the class. Pass `params` to `ScalaDoc` |
| A generated file has no `.generated` in its name | A generator registers it by path. Make the path with `toGeneratedPath` |
## The reference SDK
The style of the Scala output follows a hand-written SDK:
`softwaremill/sttp-ai` (the OpenAI module), at commit
`94567952086ba1ed8b7778f001feb08a5ba653a9`, Apache-2.0. Its authors
wrote sttp, and it uses sttp client 4 with circe, as the generated code
does. The source is Scala 2 style, because the project cross-builds.
The generated code keeps its shapes and uses the Scala 3 form.
Conventions that the generated code follows:
1. Models are plain case classes. The file of a model has the name of
its main type. Each is a `final case class`.
2. Types are `PascalCase` and fields are `camelCase`. No field has its
wire name on it: the codec holds the name (`ship_to` is the field
`shipTo`).
3. A reserved word is in backticks, and keeps its name: `` `type` ``.
4. A value that is optional and a value that can be `null` are both
`Option[T]`. An optional field has the default `None`. Required
fields need no default, and they come first.
5. A field with one possible value has that value as its default.
6. A map is `Map[String, V]`, and free-form JSON is `io.circe.Json`.
7. A string enum is a Scala 3 `enum` with the wire value on each case.
Its codec finds the case by its value. The enum has a fixed set of
cases: the decoder fails for an unknown value.
8. A union with a discriminator is a closed type with one case for each
member. The codec reads the discriminator and then the member.
9. `number` is `Double`.
10. A comment is Scaladoc on the type, with one `@param` for each field.
The description is on the next line, indented. A method has a
summary line and then its `@param` lines.
11. Codecs are explicit, one for each type.
12. The client is one class that takes the base URI and the fixed
headers in its constructor.
13. A method describes a request and does not send it. Its type is
`Request[Either[Error, T]]`, and the caller sends it with a backend.
14. A path parameter is a plain argument. A query parameter or a header
with `required: false` is an `Option[T]` with the default `None`. A
required one is a plain argument. The client adds each part of the
path to the URI, and joins no strings.
15. The request body is one argument, the body class.
16. One shared piece of code reads the response and maps a status that
is not a success to an error. A method gives an error in the
`Either`, and does not throw it.
17. The runtime is small and hand-written (`base-files/Client.scala`).
The generated code is the part that the document changes.
Where the generated code differs, and why:
- An array is `List[T]`. The reference uses `Seq[T]`. One collection
type is in use everywhere.
- Each codec is a `given` in the companion of its type. The reference
has one file of codecs, with `implicit val`.
- The generator writes each codec field by field, and derives none. Such
a codec holds a wire name that is not the field name with no
`Configuration` import. It decides between `null` and an absent key
itself. It also holds the keys of a map beside the declared fields.
- A date keeps no wire type. The reference keeps a date as Unix seconds
in an `Int`, and has no `java.time`. The generated code reads
`format: date-time` as `OffsetDateTime`, `date` as `LocalDate` and
`uuid` as `UUID`.
- `integer` with `format: int32` is `Int`, and with no format it is
`Long`. The reference uses `Int` for each integer. An `Int` fails to
decode an id above 2,147,483,647.
- A union with a discriminator is an `enum` with one case that holds
each member. The reference has a sealed trait that each member
extends. A member can then be in two unions, and the generator needs
no search of the document.
- The value of each case of such an `enum` comes from the `enum` of the
discriminator property in the member. The reference takes it from
`discriminator.mapping`. The encoder of the member then writes the
value that the decoder reads. A member with no such `enum` makes the
union `Json`, because core's `OasUnion.isDiscriminable()` does not
read `mapping`.
- A union with no discriminator is `Json`. The reference has a sealed
trait for each union.
- The name of a method comes from its HTTP method and its path
(`getApiPetsPetId`). The reference has a verb and a noun (`listPets`).
- Query parameters are arguments of the method, as in the OpenAPI
Generator `scala-sttp4` output. The reference has a parameter class
for each operation.
Not for a default generator: retries, a second client that throws,
streams, exception classes for each status code, convenience overloads
and pagination helpers.