3

How can I implement a Class which can ask just like Array, providing indexed setter?

like:

val k = new MyKls(size) k(0) = 2 //<<-- I want this kind of functionality. 

Thanks.

1 Answer 1

8

It sounds like what you are looking for is the update method. If you define this method, then Scala will use it in the k(0) = 2 syntax. It is similar to the apply method which allows you do use the k(0) accessor syntax.

Here's a short example:

import scala.collection.mutable.Buffer class MyKls(size: Int) { val buf = Buffer.fill(size)(0) def apply(index: Int) = buf(index) def update(index: Int, newValue: Int) { buf(index) = newValue } override def toString = buf.mkString("[", ", ", "]") } val k = new MyKls(5) println(k) // [0, 0, 0, 0, 0] k(0) = 2 println(k) // [2, 0, 0, 0, 0] println(k(0)) // 2 

You can find some more detail here.

Sign up to request clarification or add additional context in comments.

1 Comment

This question may also be useful in understanding the other special methods: stackoverflow.com/q/1483212/547212

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.