C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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
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
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