简体   繁体   中英

A way to simulate indexed access for Class in Scala

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM