Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use java.String.format in Scala?

I am trying to use a .format method of a string. But if I place %1, %2, etc. in the string, java.util.UnknownFormatConversionException is thrown pointing to a confusing Java source code piece:

private void checkText(String s) {      int idx;      // If there are any '%' in the given string, we got a bad format     // specifier.     if ((idx = s.indexOf('%')) != -1) {         char c = (idx > s.length() - 2 ? '%' : s.charAt(idx + 1));         throw new UnknownFormatConversionException(String.valueOf(c));     } } 

From this I understand that % char is forbidden. If so, then what should I use for argument placeholders?

I use Scala 2.8.

like image 952
Ivan Avatar asked Sep 12 '10 14:09

Ivan


People also ask

How to format string in Scala?

In Scala Formatting of strings can be done utilizing two methods namely format() method and formatted() method. These methods have been approached from the Trait named StringLike.

Can you format strings in Java?

In java, String format() method returns a formatted string using the given locale, specified format string, and arguments. We can concatenate the strings using this method and at the same time, we can format the output concatenated string.


1 Answers

While all the previous responses are correct, they're all in Java. Here's a Scala example:

val placeholder = "Hello %s, isn't %s cool?" val formatted = placeholder.format("Ivan", "Scala") 

I also have a blog post about making format like Python's % operator that might be useful.

like image 190
pr1001 Avatar answered Sep 21 '22 09:09

pr1001