Scala学习笔记27【泛型类、泛型方法、Bounds入门实战】

Scala泛型类、泛型方法的定义使用

package com.yl.scala

abstract class Stack[A]{          //'A'是Stack类及其子类的类型参数。
  def push(x: A): Stack[A] = new NonEmptyStack[A](x, this)
  def isEmpty: Boolean
  def top: A
  def pop: Stack[A]
}

class EmptyStack[A] extends Stack[A] {
  def isEmpty = true
  def top = error("EmptyStack.top")
  def pop = error("EmptyStack.pop")
}

class NonEmptyStack [A](elem: A, rest: Stack[A]) extends Stack[A] {
  def isEmpty = false
  def top = elem
  def pop = rest
}

object ScalaGenericClass {
  def main(args: Array[String]){

    //使用泛型类
    val x = new EmptyStack[Int]   //创建了存放Int类型的空栈,中括号内的类型实参[Int]对应定义中的类型参数A。
    val y = x.push(1).push(2).push(4)
    println("y.top = " + y.top)
    println(y.pop.top)

    //泛型方法定义及使用:判断一个栈是不是另一个栈的前缀(prefix)
    def isPrefix[A](p: Stack[A], s: Stack[A]): Boolean = {
      p.isEmpty || p.top == s.top && isPrefix[A](p.pop, s.pop)
    }  

    val s1 = new EmptyStack[String].push("abc")
    val s2 = new EmptyStack[String].push("abx").push(s1.top) //s2: "abc", "abx"
    println("s1.top = " + s1.top)
    println("s2.top = " + s2.top)
    val result = isPrefix[String](s1, s2) //[String]可选,Scala可以自动推断类型
    println("result = " + result)
  }
}

运行结果:

y.top = 4
2
s1.top = abc
s2.top = abc
result = true

Scala泛型类之界限Bounds示例:

package com.yl.scala

//上界  示例:T类型必须是Compare类的子类 
class Pair_Up[T <: Comparable[T]](val first: T, val second: T){
  def bigger = if(first.compareTo(second) > 0) first else second
}

//下界  示例: R一定是T的父类
class Pair_Lower[T](val first: T, val second : T){
  def repalceFirst[R >: T](newFirst: R) = new Pair_Lower[R](newFirst, second)
}

object ScalaBounds {
  def main(args: Array[String]){
 val a = new Pair_Up("Spark", "Hadoop")
 println("a.first = " + a.first)
 println("a.second = " + a.second)
 println("a.bigger = " + a.bigger)
  }
}
/*运行结果

a.first = Spark
a.second = Hadoop
a.bigger = Spark

*/

你可能感兴趣的:(scala,泛型,bounds)