What is lastIndexOf in Scala?

Scala offers many functions for string manipulation, including lastIndexOf. The lastIndexOf function searches for the occurrence of a specified character (or characters), and then returns the index of the last position at which it is found.

Syntax

int lastIndexOf(string find)

Parameter

The lastIndexOf function takes only one parameter: a string find, the character (or characters) whose last index position is required.

Return value

The lastIndexOf function returns the last index at which it finds the specified character in the argument. If the character is not in the text, the function will return -1.

Code

The following code shows how we can implement the lastIndexOf function.

// Example code for lastIndexOf() function
object Main extends App{
//Using lastIndexOf function with substring
val index = "This is an Edpresso shot".lastIndexOf("shot")
// Displays last index of character
println(index)
//Using lastIndexOf function with a single character
val index_2 = "This is an Edpresso shot".lastIndexOf("s")
// Displays last index of character
println(index_2)
// When the character is not in the string
val not_found = "This is an Edpresso shot".lastIndexOf('x')
// Displays -1 i.e. character not found
println(not_found)
}

Free Resources

Copyright ©2026 Educative, Inc. All rights reserved