Reputation: 70
I am trying to use String.format to replace substring in Scala. I am having substring values in Array[String]
Code below:
val Input_Query = "select * from table where arg_1 = %s and arg_2 = %s"
val str1 = "2019_09"
val dbpairs = str1.split("_")
val query = Input_Query.format(dbpairs)
Expected output:
select * from table where arg_1 = 2019 and arg_2 = 09
Error:
java.util.MissingFormatArgumentException: Format specifier '%s' at java.util.Formatter.format(Formatter.java:2519) at java.util.Formatter.format(Formatter.java:2455)
Upvotes: 1
Views: 343
Reputation: 4491
Your problem is you are trying to pass array argument to varargs method format
.
problem in line:
val query = Input_Query.format(dbpairs)
format
signature is:
def format(args : Any*): String
Any*
means it accepts one or more elements of Any
type.
your code should be:
val Input_Query = "select * from table where arg_1 = %s and arg_2 = %s"
val str1 = "2010_09"
val dbpairs: Array[String] = str1.split("_")
val query = Input_Query.format(dbpairs:_*)
println(query) // select * from table where arg_1 = 2010 and arg_2 = 09
when you call varargs method you should pass it with :_*
syntax, not just passing Array
or Seq
.
In your case you can use string interpolation also.
useful links:
Upvotes: 1