Shubhankar Dimri
Shubhankar Dimri

Reputation: 303

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?

Upvotes: 5

Views: 3369

Answers (1)

Sam
Sam

Reputation: 9944

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) {
    ...

Upvotes: 11

Related Questions