You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala:非宏方式实现内联方法中带类型占位符的动态编译错误?

内联方法/子句中生成动态编译器错误信息

是否可以在内联方法或子句中生成动态的编译器错误信息?

以下是两种现有实现方式:

1. 基于@implicitNotFound注解的声明式自定义

通过方法上下文参数召唤实例时,可借助@implicitNotFound注解声明式自定义错误信息,该注解支持字面量字符串和类型占位符:

import scala.annotation.implicitNotFound
        
inline def singleInhabitantOf[A](using @implicitNotFound("The received type ${A} is not a singleton") voA: ValueOf[A]): A =
   voA.value
    
singleInhabitantOf[Option[Int]] // 编译错误:The received type Option[Int] is not a singleton

2. 基于summonFrom+error的命令式自定义

如果用summonFrom实现隐式实例召唤,可调用error方法命令式生成错误信息,但该方法仅支持字面量字符串,不支持类型占位符:

import scala.compiletime.{summonFrom, error}
        
inline def singleInhabitantOf2[A]: A = summonFrom {
    case voA: ValueOf[A] => voA.value
    case _ => error("The received type ${A} is not a singleton")    
}

singleInhabitantOf2[Option[Int]] // 编译错误:The received type ${A} is not a singleton

疑问

除宏之外,是否存在一种方式,既能像summonFrom那样在方法体内召唤隐式实例,同时支持类型占位符,甚至实现更灵活的动态字符串插值?

内容的提问来源于stack exchange,提问作者Readren

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 19:18:38