list - 无法推断参数类型

标签 list scala generics

我创建了 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/

相关文章:

c# - 当参数计数小于 List.Count 时出现 FindLastIndex ArgumentOutOfRangeException

java - 保持矩形的角准确

objective-c - 在 Swift 中使用 Objective-C 轻量级泛型类型为类型参数提供 AnyHashable

python - 如何将 map 列表转换为 python 中的集合 map ?

带有泛型参数的 Scala 方法调用似乎不是多态的——出了什么问题

java - 从 T 到 T 的 map

scala - 在 Scala 中通过委托(delegate)装饰(如 kotlin)

generics - 对泛型感到困惑

c# - 使用约束定义/引发通用事件

python - 更新/附加到 JSON 字典中的列表