Semantic of startsWith on Arrays

十年热恋 提交于 2019-12-14 02:12:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!