Scala 和 SLF4J :: 传递多个参数 [英] Scala and SLF4J :: pass multiple parameters
问题描述
有以下代码:log.info("参数{}和{}", param1, param2)在 Scala 中与 SLF4J 一起编译并运行良好
Having the following code: log.info("parameters {} and {}", param1, param2) compiles and works well with SLF4J in Scala
但是如果我想传递更多的参数,我需要使用数组:
However if I want to pass more arguments, I need to use Array:
log.info("parameters {} and {} and {}", Array(param1, param2,param3))
它简单地用 array.toString 替换第一个参数,而不绑定其余参数.
which simply substitutes first parameter with array.toString and leaves rest of parameters unbound.
以下代码
log.info("parameters {} and {} and {}", Array(param1, param2,param3) : _*)
无法编译,因为:
error: overloaded method value info with alternatives:
(org.slf4j.Marker,java.lang.String)Unit <and>
(java.lang.String,java.lang.Throwable)Unit <and>
(java.lang.String,Array[java.lang.Object])Unit <and>
(java.lang.String,Any)Unit
cannot be applied to (java.lang.String, Any)
log.info("parameters {} and {} and {}", Array(param1, param2,param3) : _*)
我在这里遗漏了什么?
推荐答案
我想这完全取决于推断的类型.采用数组的 log.info 方法需要一个 Array[AnyRef].所以作为演员的替代品,你可以做
I guess it all depends on the inferred type. The log.info method that takes an array is expecting an Array[AnyRef]. So as an alternative to the cast you could do
log.info("parameters {} and {} and {}", Array[AnyRef](1, 2, "a"): _*)
但这不会起作用,因为对 Int -> AnyRef 之间的隐式转换有限制.对于那些,你需要一个类型归属:
But this won't work as there's a restriction on implicit conversions between Int -> AnyRef. For those, you'll need a type ascription:
log.info("parameters {} and {} and {}",
Array[AnyRef](1: Integer, 2: Integer, "a"): _*)
查看此问题了解更多详情:隐式转换的结果类型必须比 AnyRef 更具体
See this question for more details: Result type of an implicit conversion must be more specific than AnyRef
这篇关于Scala 和 SLF4J :: 传递多个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!