我创建了 MyList
抽象类来实现列表,不使用现有列表实现的原因是我正在学习 Scala,这是同一门类(class)的练习。我正在编写一个 zipWith
函数来创建一个新列表,其中包含单个项目的连接,例如:
列表 1:列表 = [1,2,3]
list 2:listOfStrings = ["Hello", "This is", "Scala"]
我期待这样的输出:[1-Hello, 2-This is, 3-Scala]
我编写了如下所述的 zipWith
函数:
override def zipWith[B, C](list: MyList[B], zip: (A, B) => C): MyList[C] = {
if(list.isEmpty) throw new RuntimeException("Lists do not have the same length")
else new Cons(zip(h, list.head), t.zipWith(list.tail, zip))
}
我正在尝试使用以下语句调用此函数:
println(list.zipWith[String, String](listOfStrings, (Int,String)=>_+"-"+_))
但是我得到一个错误:
I could not infer the type of the parameter $3 of expanded function: ($3, _$4) => _$3 + "-" + _$4.
这个变量的类型被清楚地提到为 Int
我仍然收到这个错误。这可以使用以下方法解决:
println(list.zipWith[String, String](listOfStrings, _+"-"+_))
我无法理解为什么前面的语句失败,即使在给出所需变量的类型之后也是如此
最佳答案
语法 (Int,String)=>_+"-"+_
并不代表您的想法。
它表示一个函数,该函数接受两个具有名称但类型未知的参数:(Int: ???, String: ???) => _+"-"+_
。
因此编译器会报错,因为它确实不知道类型。
你应该:
- 用显式变量名编写它:
(i: Int, s: String) => s"$i-$s"
。 (注意插值的使用,建议不要添加 int 和 string), - 或者像这样单独声明函数:
val f: (Int, String) => String = _+"-"+_
。
关于list - 无法推断参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74948780/