I want to concatenate string with separator "/".
val s1 ="a"
val s2 ="b"
val s3 ="c"
Option1
s"$s1/$s2/$s3"
Option2
Seq(s1,s2,s3).mkString("/")
Can anyone please help to understand if which method is better
mkString is certainly neater, and much more expandable.
Say you have a number of values:
val a = 1
val b = 2
val c = 3 //etc
Either method will do the same job, and both look relatively neat when written out:
s"$a/$b/$c"
Seq(a, b, c).mkString("/")
However when you get more and more values, you will see that the mkString option is just so much easier to manage. Say you have a bunch of values (represented by numbers in the below example). Writing them all out looks very ugly, and you are prone to mistakes (missing out a value, forgetting a slash, etc). Putting them in a mkString block makes your code much neater and more manageable (in my opinion):
"1/2/3/4/5/6/7/8/9/10/11/12/13/14/15/16/17/18/19/20/21/22/23/24/25/26/27/28/29/30/31/32/33/34/35/36/37" // etc
val seq = 1 to 100
seq.mkString("/")
The above example may seem trivial, but often you won't know exactly what is in your sequence of values so mkString seems to me to be much more future-proof and neater. Whether or not they do the same thing, in my opinion it is important to keep your code readable. "Here's some stuff. Now I will make a String out of them and separate them by slashes" is much easier for me to understand than "here is a long String with slashes and stuff in it".
That's how I would do it in a real-life setting. I don't know the performance implications of either technique as I've never had to concatenate huge Strings before, but I guess how you tackle it is completely up to you, and if your data is as small and trivial as in your example I don't think it really matters. Maybe I just don't like seeing $ everywhere...
s"$a/$b/$c" is obviously much neater. Just look at all those majestic dollar signs separated by those gorgeous forward slashes!
import scala.language.reflectiveCalls; import scala.language.postfixOps; object ┏ { def apply(a: String) = new { def ┛┗(b: String) = new { def ┓┗(c: String) = new { def ┛ = a + "/" + b + "/" + c } } } } val O_o = "a"; val o_O = "b"; val o_o = "c"; val partyTime = ┏(O_o)┛┗(o_O )┓┗(o_o)┛ ; println(partyTime)