Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access primary constructor variable inside a function in Kotlin?

As per leetcode problem here following snippet of code is provided

class NumArray(nums: IntArray) {

fun sumRange(i: Int, j: Int): Int {
    
}

}

Now to access the nums array inside fun sumRange I have modified the snippet like below:

    class NumArray(nums: IntArray) {

    // added line below
    var _nums = nums

    fun sumRange(i: Int, j: Int): Int {
        
    }
}

With this I am able to access _nums inside sumRange() and I wanted to ask if there is some other way to directly access the nums variable inside the class method?

like image 894
Shubhankar Dimri Avatar asked Sep 03 '26 22:09

Shubhankar Dimri


1 Answers

Yes, there is a more succinct way! You can declare a val or var directly as part of the primary constructor. Try changing your constructor to this:

class NumArray(val nums: IntArray) {
    ...
like image 65
Sam Avatar answered Sep 07 '26 07:09

Sam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!