Scala练习题01:取列表最后一个元素
发布时间
阅读量:
阅读量
// Scala:Find the last element of a list.
// Scala:找出列表中最后一个元素
// 示例:
// scala> last(List(1, 1, 2, 3, 5, 8))
// res0: Int = 8
package com.yl.problem
object Problem01 {
def main(args: Array[String]){
//1、Scala内置的方法实现 List.last
def lastBuiltin[A](ls: List[A]): A = ls.last
println("Scala内置的方法实现结果:" + lastBuiltin(List(1, 1, 2, 3, 5, 8)))
println("Scala内置的方法实现结果:" + lastBuiltin(List(1, 3, 4, 5, 7, 9)))
//2、利用Scala的模式匹配实现
def lastRecursive[A](ls: List[A]): A = ls match {
case h :: Nil => h
全部评论 (0)
还没有任何评论哟~
