Get current line number in Kotlin
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.
|
1 2 3 4 |
fun main() { val currLine = Throwable().stackTrace[0].lineNumber println("The current line is $currLine") } |
Output:
The current line is 2
You can also use the Exception class, since it extends Throwable.
|
1 2 3 4 |
fun main() { val currLine = Exception().stackTrace[0].lineNumber println("The current line is $currLine") } |
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.
|
1 2 3 4 5 6 7 |
val lineNumber: Int get() = Throwable().stackTrace[0].lineNumber fun main() { val currLine = lineNumber println("The current line is $currLine") } |
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.
|
1 2 3 4 5 6 7 |
val lineNumber: Int get() = Thread.currentThread().stackTrace[2].lineNumber fun main() { val currLine = lineNumber println("The current line is $currLine") } |
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.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)