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

后端 未结 4 631
遇见更好的自我
遇见更好的自我 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:59

    Cast your variable to AnyRef by doing something like this:

    h(1.asInstanceOf[AnyRef], 2.asInstanceOf[AnyRef])
    

    Why?

    In scala not everything extends Object (aka AnyRef) in the way that it would in java. Specifically primitives extend AnyVal, so if your function requires an AnyRef you'll need to cast / convert / restrict your scala variables.

    There's a good discussion here: What are the relationships between Any, AnyVal, AnyRef, Object and how do they map when used in Java code?

提交回复
热议问题