6

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?

1 Answer 1

12

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) {
    ...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.