Skip to content

Folded and Literal Block Scalars

Mihai edited this page Mar 29, 2020 · 4 revisions

Support for simple and multi-line (block) scalars:

Put the bellow in a YAML file called scalars.yml and read it

simple: plain_scalar
folded: >
  a long line split into
  several short
  lines for readability
literal: |
  line 1
  line 2
  line 3
final YamlMapping map = Yaml.createYamlInput("scalars.yml").readYamlMapping();
final String folded = map.foldedBlockScalar("folded");
final Collection<String> literalLines = map.literalBlockScalar("literal");

YAML Plain Scalars

A Yaml scalar is basically a simple string. In the following example, "value" is what we call a Scalar.

key: value

The above is actually called a Plain Scalar, since it's a single sentence mapped to a key, no fancy stuff.

YAML Block Scalars

In YAML, you can also write Scalar values on multiple lines, and in this case it is called a Block Scalar. There are two types of Block Scalars:

YAML Folded Block Scalar (parent line ends with >)

  folded: >
    a long line split into
    several short
    lines for readability

The thing about Folded Block Scalars is that the new lines will not be taken into account, so when reading the above Scalar, the whole thing will be on a single line. Folded => "don't care about New Lines"

YAML Literal Block Scalar (parent line ends with |)

  literal: |
    line 1
    line 2
    line 3

In Literal Block Scalars the new lines are respected, so when you read it, you will get multiple lines. Literal => "DO care about New Lines"