Scala 隐式参数与转换的深入探究
1. 改进错误信息
在 Scala 中,当使用 map 方法处理自定义目标类型,而该类型没有对应的 CanBuildFrom 定义时,会触发特定错误。例如:
case class ListWrapper(list: List[Int])
List(1,2,3).map[Int,ListWrapper](_ * 2)
运行上述代码会得到错误信息:
<console>:10: error: Cannot construct a collection of type ListWrapper
with elements of type Int based on a collection of type List[Int].
List(1,2,3).map[Int,ListWrapper](_*2)
^
这一错误信息并非编译器在找不到隐式参数的隐式值时的默认信息。 CanBuildFrom 使用了 scala.annotation.implicitNotFound 注解来指定错误信息的格式,其声明如下:
@implicitNotFound(msg =
"Cannot cons
超级会员免费看
订阅专栏 解锁全文
474

被折叠的 条评论
为什么被折叠?



