美文网首页
Scala多态函数

Scala多态函数

作者: 小样do | 来源:发表于2019-01-30 15:25 被阅读0次
object Main extends App {

  def isSorted[A](as: Array[A], ordered: (A, A) => Boolean): Boolean = {
    @annotation.tailrec //尾递归注解,如果编辑器无法将其转化为循环则编译报错
    def loop(n: Int): Boolean = {
      if (n >= as.length) return true
      if (!ordered(as(n), as(n - 1))) return false
      else loop(n + 1)
    }
    loop(1)
  }


  val array = Array("2", "3", "5", "6")

  //def ordered(a: Int, b: Int) = if (a.>=(b)) true else false
  def ordered(a: String, b: String) = if (a.toInt >= (b.toInt)) true else false

  println(isSorted(array, ordered))

}

相关文章

网友评论

      本文标题:Scala多态函数

      本文链接:https://www.haomeiwen.com/subject/pklcsqtx.html