如何在scala中使用ListBuffer?
我有一种情况,我将单个元素列表传递给方法.在此方法中,列表中的单个元素增加1.因此,在方法调用之后,将修改列表第一个元素(递增1).
代码是这样的: val ct = List(5) someMethod(ct) println (ct(0)) // should print 6 …… //within somethod,I incrment the element like: def someMethod(ct: List[Int}) { ct(0) = ct(0) + 1 } 当然上面的代码在Scala中不起作用.我看了ListBuffer,但我发现scala doc难以理解. Scala doc分为2组:Type Member和Value Members.在类型成员中有类WithFiler,值成员有许多方法.我如何使用WithFiler(可能与此问题没有直接关系,但我想了解如何使用scala doc). 如果我想要具有非常高的性能(someMethod被称为数百万次),ListBuffer似乎是解决这个问题的正确方法(如果我错了,请纠正我). 那么如果ListBuffer是正确的列表类型如何解决上述问题,如果不是解决方案是什么? 解决方法
在scala中,表达式为:
ct(0) = ct(0) + 1 被重写为: ct.update( 0,ct.apply(0) + 1 ) 没有为超类型List定义方法更新,因为列表可以是不可变的.但是,这是函数参数的类型. 所以你必须只使用ListBuffers(或一个可变的超类型): def someMethod(ct: ListBuffer[Int]) { ct(0) = ct(0) + 1 } scala> val lst = ListBuffer( 5 ) lst: scala.collection.mutable.ListBuffer[Int] = ListBuffer(5) scala> someMethod( lst ) scala> lst res2: scala.collection.mutable.ListBuffer[Int] = ListBuffer(6) 顺便说一句,如果您需要通过索引访问元素,请使用ArrayBuffer.它应该作为java ArrayList工作. 最后,如果你不需要考虑WithFilter的东西.只需使用过滤方法. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |