问题
I was caught off guard by this expression:
val words = strings.map(s => s.split(“,”)) // split CSV data
val nonHashWords = words.filter(word => word.startsWith(“#”))
This construction is faulty, as words is a Seq[Array[String]] instead of the intented Seq[String].
I didn’t expect that Array would have a startsWith method, so I played a bit with it to understand its semantics. I naturally expected this to be true: Array(“hello”, “world”).startsWith(“hello”)
Here’s the rest of my exploration session:
scala> val s = Array("hello","world")
s: Array[String] = Array(hello, world)
scala> s.startsWith("hello")
res0: Boolean = false
scala> s.startsWith("h")
res1: Boolean = false
scala> val s = Array("hello","hworld")
s: Array[String] = Array(hello, hworld)
scala> s.startsWith("h")
res3: Boolean = false
scala> s.startsWith("hworld")
res4: Boolean = false
scala> s.toString
res5: String = [Ljava.lang.String;@11ed068
scala> s.startsWith("[L")
res6: Boolean = false
scala> s.startsWith("[")
res7: Boolean = false
What is the expected behavior of ‘array.startsWith’ ?
回答1:
Following the docs:
def startsWith[B](that: GenSeq[B]): Boolean Tests whether this mutable indexed sequence starts with the given sequence.
So array.startsWith(x) expects x to be a sequence.
scala> val s = Array("hello","world")
scala> s.startsWith(Seq("hello"))
res8: Boolean = true
What happens in the question above is that the string passed as parameter is evaluated as a sequence of characters. That leads to no compiler error although in that specific case it will not yield the expected result.
This should illustrate that:
scala> val hello = Array('h','e','l','l','o',' ','w','o','r','l','d')
hello: Array[Char] = Array(h, e, l, l, o, , w, o, r, l, d)
scala> hello.startsWith("hello")
res9: Boolean = true
来源:https://stackoverflow.com/questions/37192390/semantic-of-startswith-on-arrays