0Pricing
Scala for Backend Engineering & Functional Programming · Урок

Цитаты и вставки

Код как данные

«Цитаты и вставки» — бесплатный урок Scala for Backend Engineering & Functional Programming на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Scala for Backend Engineering & Functional Programming, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Scala for Backend Engineering & Functional Programming содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Code as Data

Scala 3 metaprogramming treats code as data. A quote captures a piece of code as an Expr, and a splice inserts an Expr back into code.

The Quote: '{ ... }

'{ expr } turns an expression into an Expr[T]. The code is not run — it becomes a value the macro can manipulate.

import scala.quoted.*

def greeting(using Quotes): Expr[String] = '{ "Hello, " + "world" }

The Splice: ${ ... }

${ expr } inserts an Expr into a surrounding quote, stitching generated fragments together. Quote and splice are inverses.

import scala.quoted.*

def doubled(x: Expr[Int])(using Quotes): Expr[Int] = '{ ${ x } * 2 }

Splicing Lifted Values

Inside a quote you can splice a value lifted with Expr(...) to embed a compile-time constant into generated code.

import scala.quoted.*

def addN(x: Expr[Int], n: Int)(using Quotes): Expr[Int] =
  '{ ${ x } + ${ Expr(n) } }

Building Code Recursively

Macros build complex expressions by combining quotes and splices in loops or recursion — for example unrolling a power into repeated multiplication.

import scala.quoted.*

def pow(x: Expr[Double], n: Int)(using Quotes): Expr[Double] =
  if (n == 0) '{ 1.0 } else '{ ${ x } * ${ pow(x, n - 1) } }

Pattern Matching on Quotes

You can destructure code by matching against quote patterns. This inspects the shape of an expression to optimize or rewrite it.

import scala.quoted.*

def optimize(e: Expr[Int])(using Quotes): Expr[Int] = e match {
  case '{ ($a: Int) + 0 } => a
  case _                  => e
}

Type[T] and Quoted Types

Just as Expr[T] carries an expression, Type[T] carries a type. Use '[T] to quote a type and given Type[T] to splice it where a type is needed.

import scala.quoted.*

def typeName[T](using t: Type[T], q: Quotes): Expr[String] =
  Expr(Type.show[T])

The reflect API

For lower-level work, quotes.reflect exposes the abstract syntax tree (Term, Symbol, TypeRepr) so you can inspect or build code beyond what quotes express directly.

import scala.quoted.*

def show(e: Expr[Any])(using q: Quotes): Expr[String] = {
  import q.reflect.*
  Expr(e.asTerm.show)
}

Round-Trip Between Levels

Convert an Expr to a Term with asTerm and back with asExpr / asExprOf[T]. This bridges the high-level quote API and the reflection API.

import scala.quoted.*

def ident[T: Type](e: Expr[T])(using q: Quotes): Expr[T] = {
  import q.reflect.*
  e.asTerm.asExprOf[T]
}

Runtime Analog

The recursive power macro above expands to plain multiplications. This self-contained runtime version shows the same result the generated code would produce.

object Main {
  def pow(x: Double, n: Int): Double =
    if (n == 0) 1.0 else x * pow(x, n - 1)
  def main(args: Array[String]): Unit = {
    println(pow(3.0, 2)) // 9.0
  }
}

Quote and Splice Are Inverses

Remember the duality: '{ } lifts code into an Expr; ${ } drops an Expr back into code. Nesting them correctly is the heart of building macros.

Quick Check

What does the splice operator ${ x } do inside a quote?

Recap

You learned quotes and splices:

  • '{ } quotes code into Expr[T]
  • ${ } splices an Expr into code
  • quote pattern matching to destructure code
  • Type[T] and the reflect API

Next: practical macros.

Часто задаваемые вопросы

Урок «Цитаты и вставки» бесплатный?

Да — полный текст урока «Цитаты и вставки» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Scala for Backend Engineering & Functional Programming, подпишись на CoddyKit PRO. Курс Scala for Backend Engineering & Functional Programming содержит 4 уроков всего.

Чему я научусь в уроке «Цитаты и вставки»?

Код как данные Ты практикуешь Scala for Backend Engineering & Functional Programming с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Scala for Backend Engineering & Functional Programming?

Предыдущий опыт не требуется. Scala for Backend Engineering & Functional Programming на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.

Сколько времени занимает урок «Цитаты и вставки»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Scala for Backend Engineering & Functional Programming?

Да. Каждый урок Scala for Backend Engineering & Functional Programming включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Встраиваемые методы
  2. Основы макросов
  3. Цитаты и вставки
  4. Практические макросы
← Назад к Scala for Backend Engineering & Functional Programming