Back to Scala3

E223: Cannot Be Included in Capture Set

docs/_docs/reference/error-codes/E223.md

3.8.42.8 KB
Original Source

E223: Cannot Be Included in Capture Set

This error occurs during capture checking when a capability reference is used inside a class or expression whose capture set does not include that reference.

Capture checking tracks which capabilities (such as mutable references or I/O handles) a piece of code may use. When a class has a restricted capture set — either explicitly declared by inheriting scala.caps.Pure or implicitly by inheriting a pure type like java.lang.Exception — any references to capabilities outside that set are rejected.

Note: This error requires the experimental capture checking feature to be enabled.


Example

scala
trait Handle:
  val id: String

trait PureParent extends caps.Pure
class Processor(val ctx: Handle^) extends PureParent // error

class ImplicitlyPure(ctx: Handle^) extends java.lang.Exception // error

def test(handle: Handle^) =
  new PureParent:
    val ctx = handle // error
    val id = ctx.id

Error

scala
-- [E223] CaptureChecking Error: example.scala:5:20 ----------------------------
5 |class Processor(val ctx: Handle^) extends PureParent // error
  |                    ^
  |Reference `Processor.this.ctx` is not included in the allowed capture set {} of the self type of class Processor.
-- [E223] CaptureChecking Error: example.scala:7:21 ----------------------------
7 |class ImplicitlyPure(ctx: Handle^) extends java.lang.Exception // error
  |                     ^
  |Reference `ImplicitlyPure.this.ctx` is not included in the allowed capture set {} of the self type of class ImplicitlyPure.
-- [E223] CaptureChecking Error: example.scala:11:8 ----------------------------
11 |    val ctx = handle // error
   |    ^^^^^^^^^^^^^^^^
   |Reference `handle` of value ctx is not included in the allowed capture set {} of the self type of anonymous class Object with PureParent {...}.

Solution

Classes extending pure types cannot hold any references to capabilities. Restructure your code to either:

  • extract required data from tracked capability so that reference is not required anymore
  • drop capture tracking
  • consider modifiyinh types hierarchy if possible
scala
trait Handle:
  val id: String

trait NonPureParrent
trait PureParent extends NonPureParrent, caps.Pure
class Processor(val ctx: Handle^) extends NonPureParrent

class ImplicitlyPure(ctx: Handle) extends java.lang.Exception

def test(handle: Handle^) =
  new PureParent:
    val id = handle.id
<!-- SOURCE-ONLY: Remove the notice below once this page has been manually updated. --> <aside class="warning"> This reference page was created with LLM assistance - the description of the error code may not be accurate or cover all possible scenarios. </aside>