IndexOfA List or String may contain many elements of different values. With Scala 3.3, 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.
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.
indexOf fails to locate a match, it returns the value -1. Often we must check for -1 before using the index.object Program {
def main(args: Array[String]): Unit = {
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)
}
}(0,white)
(1,grey)
-1IndexOf, StringWe can use the Java indexOf method in Scala. This searches the string's characters. This is a familiar method from Java.
object Program {
def main(args: Array[String]): Unit = {
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)
}
}bird cat frog
0
5
9
-1IndexOfSliceWith 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.
object Program {
def main(args: Array[String]): Unit = {
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)
}
}List(10, 20, 30)
0
-1
-1For 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.