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() functionobject Main extends App{//Using lastIndexOf function with substringval index = "This is an Edpresso shot".lastIndexOf("shot")// Displays last index of characterprintln(index)//Using lastIndexOf function with a single characterval index_2 = "This is an Edpresso shot".lastIndexOf("s")// Displays last index of characterprintln(index_2)// When the character is not in the stringval not_found = "This is an Edpresso shot".lastIndexOf('x')// Displays -1 i.e. character not foundprintln(not_found)}
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved