无法推断参数类型

Nik*_*ole 2 generics scala list

我创建了MyList抽象类来实现列表,不使用现有列表实现的原因是我正在学习 Scala,这是同一门课程的练习。我正在编写一个zipWith函数来创建一个包含单个项目串联的新列表,例如:

列表 1:列表 =[1,2,3]
列表 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))
  }
Run Code Online (Sandbox Code Playgroud)

我尝试使用以下语句调用此函数:

println(list.zipWith[String, String](listOfStrings, (Int,String)=>_+"-"+_))
Run Code Online (Sandbox Code Playgroud)

但我收到错误:

我无法推断扩展函数的参数 $3 的类型:( $3, _$4) => _$3 + "-" + _$4。

明确提到了此变量的类型,因为Int我仍然收到此错误。这可以使用以下方法解决:

println(list.zipWith[String, String](listOfStrings, _+"-"+_))
Run Code Online (Sandbox Code Playgroud)

我无法理解为什么早期的语句失败,即使在给出所需变量的类型之后也是如此

Gaë*_*l J 5

语法(Int,String)=>_+"-"+_并不意味着你的想法。

它表示一个带有两个参数的函数,这些参数具有某个名称但类型未知:(Int: ???, String: ???) => _+"-"+_

因此,编译器会引发错误,因为它确实不知道类型。

您应该:

  • 用明确的变量名称编写它:(i: Int, s: String) => s"$i-$s"。(注意插值的使用,建议使用插值而不是添加 int 和 string),
  • 或者像这样单独声明函数:val f: (Int, String) => String = _+"-"+_.