Why Split behaves differently on different Strings?

scala, split, string

Solution

In first case you provide a string and a separator that doesn't match any of characters in that string. So it just returns the original string. This can be illustrated with non-empty string example:

scala> "abcd".split('f')
res2: Array[String] = Array(abcd)

However your second string contains only separator. So it matches the separator and splits the string. Since splits contain nothing - it returns an empty array. According to Java String docs:

If expression doesn't match:

If the expression does not match any part of the input then the resulting array has just one element, namely this string.

If expression matches:

Trailing empty strings are therefore not included in the resulting array.

Source: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String,%20int)

Problem

Here are the two cases : Case 1: ``` scala> "".split('f') res3: Array[String] = Array("") ``` Case 2: ``` scala> "f".split('f') res5: Array[String] = Array() ``` Why does it behaves diffently here ! A concrete explanation would be great !

Original source