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,220
  • 17
  • 76
  • 135
borchero
  • 5,562
  • 8
  • 46
  • 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,300
  • 6
  • 28
  • 41
Isaiah Taylor
  • 615
  • 1
  • 4
  • 17