java – Scala:String“”vs“”
I am a newcomer to scala. I have seen the code for connecting strings in Scala, as shown below:
"test " ++ "1"
And I've tested it and written it in scala doc
"test " + "1"
So my understanding is that Java strings are more powerful and can accept more parameter types It also seems to be common for other things like lists I wonder if my understanding is correct And any other differences? When should one after another just for string connection?
Solution
It helps in scala Predef, see what happened
If you check there, you will find that string in scala is just Java An alias of lang.string In other words, a method on a string is converted to a Java operator
So if a Scala string is just a Java string, you may ask how this method exists (well, I'll at least ask.) the answer is that an implicit conversion from string to wrappedstring provided by the rectstring method is also in predef
Note that you need any gentraversableonce instance and add all the elements in that instance to the original wrappedstring (note that the document incorrectly declares that the method returns a wrappedstring [b], which must be incorrect because wrappedstring does not use type parameters.) What you will get is a string (if what you add is a SEQ [char]) or some indexedseq [any] (if not)
Here are some examples:
If you add a string to the list [char], you will get a string
scala> "a" ++ List('b','c','d') res0: String = abcd
If you add a string to the list [string], you get an indexedseq [any] In fact, the first two elements are chars, but the last three are strings, as shown in subsequent calls
scala> "ab" ++ List("c","d","e") res0: scala.collection.immutable.IndexedSeq[Any] = Vector(a,b,c,d,e) scala> res0 map ((x: Any) => x.getClass.getSimpleName) res1: scala.collection.immutable.IndexedSeq[String] = Vector(Character,Character,String,String)
Finally, if you add a string to a string, you will get a string The reason for this is that wrappedstring inherits from indexedseq [char], so this is a complex method. Adding SEQ [char] to SEQ [char] allows you to return SEQ [char]
scala> "abc" + "def" res0: String = abcdef
As Alexey said, these are not very subtle tools, so you may prefer to use string interpolation or StringBuilder unless there is a good reason not to