Result type of an implicit conversion must be more specific than AnyRef

后端 未结 4 637
遇见更好的自我
遇见更好的自我 2020-11-29 09:12

Let

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

and so

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

H

4条回答
  •  广开言路
    2020-11-29 09:44

    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(",")
    

提交回复
热议问题