Transforming Scala varargs into Java Object… varargs

前端 未结 2 1473
野的像风
野的像风 2020-12-09 10:55

I have a Java class that logs stuff which has a method like this:

void info(Object message, Object... params);

In Scala, I\'ve created a wr

2条回答
  •  误落风尘
    2020-12-09 11:33

    @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!

提交回复
热议问题