use*_*013 1 recursion scala brackets
我正在学习Scala。下面的代码多次出现[A]。请有人用外行的方式向我解释。我无法理解(尝试使用google并阅读StackOverflow和其他答案,但我不明白。下面的代码是从列表中找到第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
}Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)
这里[A]是函数findKth的类型参数。现在,类型参数是什么意思?类型参数告诉编译器方法findKth可以采用类型A的参数。这里的通用类型是a,因为它可以是任何东西。例如,A可以是Int,Double,Another List等。
有关更多信息,建议您通过以下链接:
| 归档时间: |
|
| 查看次数: |
537 次 |
| 最近记录: |