2

In Apple's programming language Swift, you can use subscript as you do in arrays for your own class. For example a class in Swift could look like this:

class MyNumber {
    let value: Int
    init(value: Int) {
        self.value = value
    }
    subscript(i: Int) -> Int {
        return value * i
    }
}

This class only has a getter subscript but you could do a setter subscript, too. Anyway when doing this:

let number = MyNumber(value: 15)
println(number[3])

it produces the output 45.

Is it possible to write such classes using subscript in Java as well? Of course, I could simply use a method with a parameter but I wanted to know if this is possible. Thanks for any answer :)

Emil
  • 7,112
  • 17
  • 75
  • 132
borchero
  • 4,964
  • 7
  • 42
  • 72

1 Answers1

1

Short answer: no. Setting something equal to Class() in Java is creating a new instantiation of that object. Just do something like this:

var = new MyNumber(15)
var.multiply(3)

and in your MyNumber class code, change subscript to multiply for clarity. That will work the same.

A shorthand version of the same principle is

System.out.println(new MyNumber(15).multiply(3));
lukas
  • 2,140
  • 6
  • 30
  • 40
Isaiah Taylor
  • 597
  • 1
  • 4
  • 17