Scala indexOf: Lists and Strings

Call the indexOf method on Lists and Strings to locate elements within collections.

IndexOf. A List contains many elements of different values. And a String contains substrings and characters. We can search for these values and find their positions.

With indexOf, we try to find an element in a List or String. IndexOf returns an Int that tells us where it is. If nothing is found, we get the value -1.

First example. Here we use indexOf on the Scala List type. We have an immutable list of 3 Strings. We try to find elements within the List. The first one, with value "white," is at index 0.

No value: When indexOf fails to locate a match, it returns the value -1. Often we must check for -1 before using the index.

Scala program that uses indexOf val source = List("white", "grey", "black"); // Use indexOf to search the List. val white = source.indexOf("white") val grey = source.indexOf("grey") // When no element is found, the value -1 is returned. val noIndex = source.indexOf("???") // Print the results. println((white, source(white))) println((grey, source(grey))) println(noIndex) Output (0,white) (1,grey) -1

IndexOf, String. We can use the Java indexOf method in Scala. This searches the string's characters. This is a familiar method from Java.String
Scala program that uses indexOf on String val source = "bird cat frog" // Search for parts of the string. val birdIndex = source.indexOf("bird") val catIndex = source.indexOf("cat") val frogIndex = source.indexOf("frog") // This string is not found, so we get -1. val noIndex = source.indexOf("???") // Print out all the variables. println(source) println(birdIndex) println(catIndex) println(frogIndex) println(noIndex) Output bird cat frog 0 5 9 -1

IndexOfSlice. With this method, we try to find a slice within a List. We can specify the argument to indexOfSlice as a List. The entire series of values must be found for a match.
Scala program that uses indexOfSlice val source = List(10, 20, 30) // Use indexOfSlice to find a List within a List's elements. val test1 = source.indexOfSlice(List(10, 20)) val test2 = source.indexOfSlice(List(10, 900)) val test3 = source.indexOfSlice(List(30, 0)) println(source) println(test1) println(test2) println(test3) Output List(10, 20, 30) 0 -1 -1

A summary. For Scala, we have access to both Java methods and Scala-specific methods. The indexOf method on List can take 1 or 2 arguments. IndexOfSlice and indexWhere are also available.
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to