数组

时间:2016-05-12 16:17:12

标签: arrays scala collections

这个表达让我措手不及:

val words = strings.map(s => s.split(“,”)) // split CSV data
val nonHashWords = words.filter(word => word.startsWith(“#”))

这种结构有问题,因为wordsSeq[Array[String]]而不是意图Seq[String]。 我没想到Array会有startsWith方法,所以我用它来理解它的语义。我自然希望这是真的:Array(“hello”, “world”).startsWith(“hello”)

以下是我的探索课程的其余部分:

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

'array.startsWith'的预期行为是什么?

1 个答案:

答案 0 :(得分:4)

关注文档:

  

def startswith [B](即:GenSeq [B]):Boolean测试这是否可变   索引序列以给定序列开始。

因此array.startsWith(x)期望x成为序列。

scala> val s = Array("hello","world")
scala> s.startsWith(Seq("hello"))
res8: Boolean = true

上面提到的问题是,作为参数传递的字符串被评估为一系列字符。这导致没有编译器错误,尽管在那种特定情况下它不会产生预期的结果。

这应该说明:

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