Scala字符串类型不明确



我想在scala-Seq中删除一些元素,但出现了令人困惑的错误:

<console>:33: error: type mismatch;
found   : Seq[java.lang.String]
required: Seq[String(in method drop_Val_List_In_List)]
tmp;
^

什么是Seq[String(in method drop_Val_List_In_List)]

代码如下:

// Method that drops one element in sequence
def drop_Val_In_List[A](ls: Seq[A], value: A):  Seq[A] = {
val index = ls.indexOf(value)  //index is -1 if there is no matc
if (index < 0) {
ls
} else if (index == 0) {
ls.tail
} else {
// splitAt keeps the matching element in the second group
val (a, b) = ls.splitAt(index)
a ++ b.tail
}
}
val KeepCols = Seq("id", "type", "month", "car", "road")

// Generalization of the above method to drop multiple elements
def drop_Val_List_In_List[String](ls: Seq[String], in_ls: Seq[String]): Seq[String] = {
var tmp = ls
//println(tmp.getClass)
for(x <- in_ls ){ // should work without var x
tmp = drop_Val_In_List(tmp.toSeq, x.toString)
}
tmp;
}
val tmp = drop_Val_List_In_List(KeepCols, List("id", "type", "month"))

所需的输出:tmp,它包含";汽车;以及";道路";字符串

def drop_Val_List_In_List[String]声明了一个类型参数,您称之为String;真实的";String

如果要对任何类型的A执行此操作,请将其中的String更改为A。如果您只想专用于String,请删除[String],并保留def drop_Val_List_In_List(...)

我更改了一些类型,现在它可以使用

def drop_Val_In_List[String](ls: Seq[String], value: String):  Seq[String] = {
val index = ls.indexOf(value)  //index is -1 if there is no matc
if (index < 0) {
ls
} else if (index == 0) {
ls.tail
} else {
// splitAt keeps the matching element in the second group
val (a, b) = ls.splitAt(index)
a ++ b.tail
}
}

def drop_Val_List_In_List[String](ls: Seq[String], in_ls: Seq[String]): Seq[String] = {
var tmp_ = ls
//println(tmp.getClass)
for(x <- in_ls ){ // should work without var x
println(x)
tmp_ = drop_Val_In_List(tmp_, x)
} 
tmp_
}
val KeepCols = Seq("ctn", "type", "month", "car", "road")
val tmp = drop_Val_List_In_List(KeepCols, List("ctn", "type", "month"))// Start writing your ScalaFiddle code here
println(tmp)
// Start writing your ScalaFiddle code here

最新更新