From d5de65fdb1802cdf498d65d93397f290813c377c Mon Sep 17 00:00:00 2001 From: muqiuhan Date: Tue, 9 Sep 2025 06:17:00 +0000 Subject: deploy: 9665097f0fa0dae9f92123fac54d26c0818758a5 --- 2025/03/25/Scala-3-Capture-Checking/index.html | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) (limited to '2025/03/25') diff --git a/2025/03/25/Scala-3-Capture-Checking/index.html b/2025/03/25/Scala-3-Capture-Checking/index.html index b7c12801..b3dcf199 100644 --- a/2025/03/25/Scala-3-Capture-Checking/index.html +++ b/2025/03/25/Scala-3-Capture-Checking/index.html @@ -213,11 +213,8 @@
  • 不安全的资源管理: 例如,传统的 try-with-resources 模式旨在确保资源在使用后被正确关闭。Capture Checking 通过跟踪与资源相关的 Capabilities,可以防止在资源关闭或失效后继续使用它的情况。文档中提到的 usingLogFile 示例就展示了这一点,其中一个闭包尝试写入一个已经关闭的文件,而Capture Checking可以捕获这种不安全的操作:
  • 1
    2
    3
    4
    5
    def usingLogFile[T](op: FileOutputStream => T): T =
    val logFile = FileOutputStream("log")
    val result = op(logFile)
    logFile.close()
    result
    -
    1
    2
    def usingLogFile[T](op: FileOutputStream^ => T): T =
    // same body as before
    -
    1
    2
    3
    4
    |  val later = usingLogFile { f => () => f.write(0) }
    | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    |The expression's type () => Unit is not allowed to capture the root capability `cap`.
    |This usually means that a capability persists longer than its allowed lifetime.
    -