Scala从列表中删除单个对象

时间:2013-04-03 20:47:09

标签: scala

我正在将一些java代码翻译成scala,我在使用列表中删除对象时遇到问题。我的代码在

之下
def removeCar (usedCarList: List[UsedCars]):List[UsedCars] ={
    //var vinNumber = "";
    var car = new UsedCars();
    println("Please enter the Vin Number");
    var vinNumber = readLine();
    var i = 0;
    var found = false;
    while (i < usedCarList.length){
        car = usedCarList(i);
        if (vinNumber == car.vinNumber) {
            usedCarList.drop(i);
            println("** Removed Car with Vin Number " + vinNumber + " **");
            println(car.vinNumber);
            found = true;
        } 

我知道drop不是我想要使用但我无法弄清楚如何在给定索引处删除元素。

1 个答案:

答案 0 :(得分:1)

正如评论中指出的那样,Scala的List采用了截然不同的方法。您仍然可以使用该类型,因为它非常简单实用,只有您不能使用drop之类的内容。在任何情况下,您使用变量 carfound while if等进行迭代,仍然非常java&#39; ish。

尝试使用Scala集合提供的映射,拆分和过滤功能。

def removeCar (usedCarsList: List[UsedCars]): List[UsedCars] ={
  println("Please enter the Vin Number")
  val vinNumber = readLine()
  val (same, different) = usedCarsList.partition(_ == vinNumber)
  if (same.nonEmpty) {
    println("** Removed Car with Vin Number " + vinNumber + " **")
    same.map(_.vinNumber).foreach(println)
  }
  different
}

如果您不关心验证列表是否已更改,您也可以执行

val removed = usedCarsList.filterNot(_ == vinNumber)

我上面使用的方法partitionright at the start of the Scala collections introduction.

相关问题