隐式转换的结果类型必须比 AnyRef 更具体 [英] Result type of an implicit conversion must be more specific than AnyRef

查看:88
本文介绍了隐式转换的结果类型必须比 AnyRef 更具体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

def h(a: AnyRef*) = a.mkString(",")h: (a: AnyRef*)String

等等

h("1","2")资源:字符串 = 1,2

然而,h(1,2)

error: 隐式转换的结果类型必须比 AnyRef 更具体h(1,2)^错误:隐式转换的结果类型必须比 AnyRef 更具体h(1,2)^

至少在 Scala 2.11.1 和 2.11.1 中是这样.询问解决方法.

解决方案

你可以简单地重现这个问题:

val x: AnyRef = 42

这是引入更改的相关 github 上的拉取请求

基本原理是出于安全原因,某些隐式转换被显式禁用,即当从 TU 的转换被禁用时,如果:

T <: 空

AnyRef <: U

在您的具体情况下,这意味着 Int(不是 AnyRef)永远不会转换为 AnyRef.>

如果您需要同时接受IntString,您可以考虑接受Any.由于每个 Scala 对象都继承自 Any,因此不需要隐式转换.

def h(a: Any*) = a.mkString(",")

Let

def h(a: AnyRef*) = a.mkString(",")
h: (a: AnyRef*)String

and so

h("1","2")
res: String = 1,2

However, h(1,2)

error: the result type of an implicit conversion must be more specific than AnyRef
              h(1,2)
                ^
error: the result type of an implicit conversion must be more specific than AnyRef
              h(1,2)
                  ^

This is at least in Scala 2.11.1 and 2.11.1. To ask on a workaround.

解决方案

You can reproduce the issue simply with:

val x: AnyRef = 42

Here's the relevant pull request on github that introduced the change

The rationale is that for security reasons some implicit conversions are explicitly disabled, namely when the conversion goes from T to U is disabled if:

T <: Null

or

AnyRef <: U

In your specific case, this means that an Int (which is not an AnyRef) will never be converted to AnyRef.

If you need to accept both Int and String, you can consider accepting Any instead. Since every scala object inherits from Any, there's no implicit conversion needed.

def h(a: Any*) = a.mkString(",")

这篇关于隐式转换的结果类型必须比 AnyRef 更具体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆