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?
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) {
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With