
- Kotlin - Home
- Kotlin - Overview
- Kotlin - Environment Setup
- Kotlin - Architecture
- Kotlin - Basic Syntax
- Kotlin - Comments
- Kotlin - Keywords
- Kotlin - Variables
- Kotlin - Data Types
- Kotlin - Operators
- Kotlin - Booleans
- Kotlin - Strings
- Kotlin - Arrays
- Kotlin - Ranges
- Kotlin - Functions
- Kotlin Control Flow
- Kotlin - Control Flow
- Kotlin - if...Else Expression
- Kotlin - When Expression
- Kotlin - For Loop
- Kotlin - While Loop
- Kotlin - Break and Continue
- Kotlin Collections
- Kotlin - Collections
- Kotlin - Lists
- Kotlin - Sets
- Kotlin - Maps
- Kotlin Objects and Classes
- Kotlin - Class and Objects
- Kotlin - Constructors
- Kotlin - Inheritance
- Kotlin - Abstract Classes
- Kotlin - Interface
- Kotlin - Visibility Control
- Kotlin - Extension
- Kotlin - Data Classes
- Kotlin - Sealed Class
- Kotlin - Generics
- Kotlin - Delegation
- Kotlin - Destructuring Declarations
- Kotlin - Exception Handling
Kotlin Array - indexOf() Function
The Kotlin array indexOf() function returns first index if the element is present in an array otherwise it returns -1.
The first index suggests that if there are two elements with the same value, this function returns the index of the first one.
Syntax
Following is the syntax of Kotlin array indexOf() function −
fun <T> Array<out T>.indexOf(element: T): Int
Parameters
This function accepts element as parameters. Which represent an element which index need to be returned.
Return value
This function returns an index. Otherwise; -1.
Example 1
Following is the basic example to demonstrate the use of indexOf() function −
fun main(args: Array<String>){ // let's create an array var array = arrayOf<Int>(1, 2, 3, 4, 5) // using indexOf val indx = array.indexOf(3) println("index of element 3: $indx") }
Output
On execution of the above code we get the following result −
index of element 3: 2
Example 2
Now, let's see another example. Here, we use the indexOf() function to display an element. Otherwise, -1 if element is not available in an array −
fun main(args: Array<String>){ // let's create an array var array = arrayOf<String>("tutorialspoint", "India", "tutorix", "India") val indx = array.indexOf("tutorials point") print("index of element: $indx") }
Output
After execution of the above code we get the following output −
index of element: -1
Example 3
The below example creates an array. We then use indexOf function. If statement will be displayed if the element is not available in the array; otherwise, the else statement will be displayed. −
fun main(args: Array<String>){ // let's create an array var array = arrayOf<Int>(1, 2, 3, 4, 5) // using indexOf val indx = array.indexOf(6) if(indx == -1){ println("the element is not available in the array!") }else{ println("element found at index: $indx") } }
Output
The above code produce following output −
the element is not available in the array!