Is there anyway to create a Scala class which is an object Array , that has an undefined number of objects in the array.
for example I can do what I want using a var
var River1 = new ArrayBuffer[RiverReach]
River1.+=(rr1,rr2,rr3)
and this works fine but i'd like a class so I can add a bunch of methods to it.At the moment I can manually add arguments in the () but the number could vary depending on the Objects. Is there a way to not set a limit? Bit of context I'm a scala beginner and i'm learning via udemy courses at the moment so please bear with me. Any help would be appreciated
Current setup. I've used ArrayBuffer as its mutable and i'll want to sum values from all the elements in the array to the head. But thats a question for a different page.
class River[T>:ArrayBuffer[RiverReach]]() {
//bunch of methods
}
You can wrap the buffer into River
, redirect River's +=
and other methods to the buffer, then add all the other functions you need, for example:
case class RiverBeach(altitude: Int)
class River {
private val buffer = new ListBuffer[RiverBeach]()
def +=(riverBeach: RiverBeach): River = {
buffer += riverBeach
this
}
def ++=(riverBeach: RiverBeach*): River = {
buffer ++= riverBeach
this
}
def size: Int = buffer.size
// your methods
}
val river = new River()
river += RiverBeach(1)
river ++= (RiverBeach(2), RiverBeach(3), RiverBeach(4))
println(river.size) // 4
Mike Allens idea was correct, after more reading better solution is to simply extend Arraybuffer
class River extends Arraybuffer[RiverReach] {
//bunch of methods
}
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.