简体   繁体   English

具有无限参数的类scala

[英]class with unlimited arguments scala

Is there anyway to create a Scala class which is an object Array , that has an undefined number of objects in the array. 无论如何,有没有要创建一个Scala类,它是一个对象Array,该对象在数组中具有未定义的对象数。

for example I can do what I want using a var 例如我可以使用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. 背景信息我是scala初学者,目前正在通过udemy课程进行学习,请耐心等待。 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. 我已经将ArrayBuffer用作其可变对象,并且我想对数组中所有元素到头部的值求和。 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: 您可以将缓冲区包装到River ,将River的+=和其他方法重定向到缓冲区,然后添加所需的所有其他功能,例如:

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 Mike Allens的想法是正确的,经过更多阅读后,更好的解决方案是简单地扩展Arraybuffer

class River extends Arraybuffer[RiverReach] {
 //bunch of methods 

 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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