Transforming Scala varargs into Java Object… varargs

我的梦境 提交于 2019-11-28 23:30:56

Found the answer:

log.info(msg,  params.map(_.asInstanceOf[AnyRef]) : _*)

The following returns a Seq[AnyRef] => params.map(_.asInstanceOf[AnyRef]), and the ': _*' part tells the compiler to pass it as varargs

Result:

"Started on 127.0.0.1:1234"

Besides, this solution deals with both AnyVals and AnyRefs

@Galder - there is an easier way which allows you to avoid the cumbersome asInstanceOf[Object] call:

def info(msg: => String, params: Any*) =  log.info( msg.format(params : _*) );

In scala 2.7, the format(args : Any*) function is implicitly included via RichString (and has a sub-optimal implementation is terms of reflection for no good reason that I can see) whereas in 2.8 the method is included via StringLike and is implemented via a direct call to String.format(String, Object ...)

I understand that the reason why Java does not contain such a method is that it has an implication that "every String is a format String", which is not the case. happily, I'm willing to forgo the logical correctness for the more useable class which scala provides!

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!