This post will discuss how to get the current line number in Kotlin.

1. Using Throwable Stack Trace

The Throwable class is the superclass of all errors and exceptions. The idea is to get an array of stack trace elements about a throwable. The first array element represents the top of the stack, which is the last function invocation in the sequence.

Download Code

Output:

The current line is 2

 
You can also use the Exception class, since it extends Throwable.

Download Code

Output:

The current line is 2

 
You should always invoke this snippet inline. If used within a function, it will return the corresponding line number in the function.

Download Code

Output:

The current line is 2

2. Using Thread Stack Trace

Alternately, you can use the stack trace of a current thread, which returns an array of stack trace elements representing the thread’s stack dump. The third element of this array of stack trace contains the stack frame of the calling function, having the current line number information.

Download Code

Output:

The current line is 5

Note that under special circumstances, some VMs may omit one or more stack frames from the stack trace. That’s all about getting the current line number in Kotlin.