本文介绍了Scala 中的黑白 Method[Int]() 与 Method() 的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在scala中看到map的方法签名后

After seeing the method signature of map in scala as

def map[A, B](l: List[A])(f: A => B): List[B] = ???

我对上面 [A, B] 的外行人的理解是,它们表明我们将在定义的方法中专门使用泛型类型 A 和 B.

my layman undersanting of [A, B] in above is that they signal the method that we'll be exclusively working with generic Type A and B in the defined method.

现在我继续实现一种方法,使用类似的编码模式从两个列表中添加值(基本上是 zipWith).

Now I go on to implement a method to add values from two lists consquetively (basically zipWith) using similar coding pattern.

def addCorresponding[Int](l1: List[Int],
                        l2: List[Int]): List[Int] =
  (l1, l2) match {
      case (_, Nil) => Nil
      case (Nil, _) => Nil
      case (x::xs, y::ys) => {
          List((x + y)) ++ addCorresponding(xs, ys)
      }
}

但是在最后一次匹配中添加元素时出现此错误:发现类型不匹配:需要 Int:字符串

but get this error while adding the elements in the last match:type mismatch found: Int Required: String

从方法签名中删除 [Int] 可修复此错误.

Removeing the [Int] from the mehtod sigature fixes this error.

我确信我对泛型类型的理解以及何时将它们添加到方法签名中存在漏洞.如果有人能引导我完成这个并解释为什么 addCorresponding 方法出现 [Int] 错误但没有它也能正常工作,我将不胜感激?

I'm sure there are holes in my understanding of generic Types and when to add them to the method signature. I'd appreciate if someone can walk me through this and explain why the addCorresponding method with [Int] errors out but works fine without it?

推荐答案

泛型方法(采用类型参数)将是

def addCorresponding[A](l1: List[A], l2: List[A]): List[A]

或者,如果列表可以有不同类型的元素

or, if the lists can have different types of elements

def addCorresponding[A, B, C](l1: List[A], l2: List[B]): List[C]

如果你实现的方法适用于具体类型 Int,那么你的方法不再是通用的:

If you implement a method that works on a concrete type Int, then your method is no longer generic:

def addCorresponding(l1: List[Int], l2: List[Int]): List[Int]

换句话说,您在此处将具体类型 Int 应用于 List[_] 而不是抽象类型参数.如果你写

In other words, you apply a concrete type Int here to List[_] instead of an abstract type parameter. If you write

def addCorresponding[Int](l1: List[Int], l2: List[Int]): List[Int]

然后你影子"具体类型Int和一个抽象类型参数Int碰巧有相同的名字;但从技术上讲,您正在编写通用方法

then you "shadow" the concrete type Int with an abstract type parameter Int that happens to have the same name; but technically you are writing the generic method

def addCorresponding[XXX](l1: List[XXX], l2: List[XXX]): List[XXX]

如果你想保持你的方法通用但对 A 类型的元素执行某些操作,你可能需要一个类型类,例如 Numeric 以算术添加元素

If you want to keep your method generic but perform certain operations on elements of type A, you may need a type class, for example Numeric to arithmetically add elements

def addCorresponding[A](l1: List[A],
                        l2: List[A])(implicit num: Numeric[A]): List[A] =
  (l1, l2) match {
    case (_, Nil) => Nil
    case (Nil, _) => Nil
    case (x::xs, y::ys) =>
      List((num.plus(x, y))) ++ addCorresponding(xs, ys)
  }

这篇关于Scala 中的黑白 Method[Int]() 与 Method() 的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 11:58