I have a Java interface like the following:
interface Bazz {
void bar(String msg, Object args...);
}
I want to implement that interface (just happens to be in Scala) and use SLF4J logging to log the args
parameter (for sake of this question, using another Scala logging library is not an option).
And the following (contrived) scala code:
object Foo extends Bazz {
private val log = LoggerFactory.getLogger(Main.getClass)
def bar(args: AnyRef*) {
log.info("Processing params: {}, {}, {}", args: _*)
// ... do stuff with args...
}
}
object Main extends App {
val arr: Seq[String] = Array("A","B","C")
val anyRef: AnyRef = arr
Foo.bar(arr)
}
}
Running Main
, I get the following output:
22:49:54.658 [run-main-0] INFO: sample.Main$ Processing params: WrappedArray(A, B, C), {}, {}
That's no good because the :_*
is exploding the args, but the first element is an array. For reasons I won't go into here, I actually need to pass the elements of that array as the single Object[]
parameter to SLF4J's Logger.info(String, Object[])
method.
Here's my first attempt:
def bar(args: AnyRef*) {
val flatArgs = args.flatMap {
case s: Seq[_] => s
case x => Seq(x)
}
log.info("Processing params: {}, {}, {}", flatArgs: _*)
// ... do stuff with args...
}
This does not compiles with the following error:
[error] Main.scala:18: overloaded method value info with alternatives:
[error] (x$1: org.slf4j.Marker,x$2: String,x$3: <repeated...>[Object])Unit <and>
[error] (x$1: org.slf4j.Marker,x$2: String)Unit <and>
[error] (x$1: String,x$2: Throwable)Unit <and>
[error] (x$1: String,x$2: <repeated...>[Object])Unit <and>
[error] (x$1: String,x$2: Any)Unit
[error] cannot be applied to (String, Any)
[error] log.info("Processing params: {}, {}, {}", flatArgs: _*)
[error] ^
[error] one error found
How can I change this code to make it compile and also print Processing params: A, B, C
?