Arvinth
Arvinth

Reputation: 70

Error while using String.format in Scala - java.util.MissingFormatArgumentException: Format specifier '%s'

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

Answers (1)

Boris Azanov
Boris Azanov

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

Related Questions