New to Scala and see people are using sign f
ahead of a string, here is an example I tried which works. Wondering what is the function of sign f
? Does it need to be combined to use with %s? Tried to search some tutorials but failed. Thanks.
object HelloWorld {
def main(args: Array[String]) {
var start = "Monday";
var end = "Friday";
var palindrome = "Dot saw I was Tod";
println(f"date >= $start%s and date <= $end%s" + palindrome);
// output date >= Monday and date <= FridayDot saw I was Tod
}
}
http://docs.scala-lang.org/overviews/core/string-interpolation.html
The f Interpolator
Prepending f to any string literal allows the creation of simple formatted strings, similar to printf in other languages. When using the f interpolator, all variable references should be followed by a printf-style format string, like %d.
PS. another somewhat related feature is http://docs.scala-lang.org/overviews/quasiquotes/expression-details
See the explanation here . For people coming from C the f
interpolator is a printf
style formatter. %
is to denote the type of data and with a $
you may may refer to a previously defined variable. The % in not mandatory. Its just that you will get a format that is decided by the compiler at compile time. Bit uyou may want to change the output format sometimes.
So if i take an example ,
var start = "Monday";
var end = "Friday";
val age = 33
var palindrome = "Dot saw I was Tod";
println(f"date >= $start and date <= $end and age<= $age%f" + palindrome);
I could omit the %f and i will see a output of 33 as it will inferred as Int. However i could use %f if i wanted to format it as a float. Also if you use a incompatible formatted you will receive a error at compile time.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.