Scala中方括号中的目的A是什么

what is the purpose A in square brackets in scala

我刚学Scala。下面的代码有 [A] 多次。请有人用外行的话向我解释一下。我无法理解(尝试 google 并阅读 Whosebug 和其他答案,但我不明白。下面的代码是从列表中找到第 k 个元素。

def findKth[A](k:Int, l:List[A]):A = k match {
    case 0 => l.head
    case k if k > 0 => findKth(k - 1, l.tail)
    case _ => throw new NoSuchElementException  
}

它用于在 Scala 中声明泛型参数,您可以使用不同类型的列表调用您的方法 (DoubleIntDogs ... )

如果你想了解更多,这个post:https://apiumhub.com/tech-blog-barcelona/scala-type-bounds/

例如:

def findKth[A](k:Int, l:List[A]):A = k match {
    case 0 => l.head
    case k if k > 0 => findKth(k - 1, l.tail)
    case _ => throw new NoSuchElementException  
}

val intList = 1 :: 2::3::4::5::6::7::8::9::10::Nil
val strList = intList.map(_.toString)
println(findKth(9, intList))
println(findKth(3, strList))

如您所见,您可以将 List[Int]List[String] 传递给您的函数,这是一种参数化函数以接受泛型参数的方法。

你可以看到它在这里工作:https://scalafiddle.io/sf/XwaALIk/0

def findKth[A](k:Int, l:List[A]):A = k match {
    case 0 => l.head
    case k if k > 0 => findKth(k - 1, l.tail)
    case _ => throw new NoSuchElementException  
}

这里[A]是函数findKth的类型参数。现在类型参数是什么意思? 类型参数告诉编译器方法 findKth 可以接受类型 A 的参数。这是通用类型,因为 A 可以是任何东西。例如 A 可以是 IntDouble、另一个 List -- 任何东西。

有关更多信息,我建议您浏览这些链接:

https://docs.scala-lang.org/tour/polymorphic-methods.html

https://docs.scala-lang.org/tour/generic-classes.html