scala generic upper bound

Scala's generics are essentially the same as Java, but the syntax is different.

It has the following uses:

The upper bound, T<:B, indicates that T is a subclass of B

The lower bound, T>:B, means that T is the father of B

There are other like, viewBound, contextBound, go back and add

 

Upper bound example: choose goddess

1. Create a new goddess class

class MissRight(val name: String, val faceValue: Int) extends Comparable[MissRight] {//必须定义为val时,才被识别为类的属性
  //这地方入参不能是T,T必须是在源中的
  override def compareTo(o: MissRight): Int = {
    this.faceValue - o.faceValue
  }
}

2. Create a new UpperBoundDemo class, which has a method to select the goddess

class UpperBoundDemo[T <: Comparable[T]] {//构造方法要不要用,但是Comparable后面必须要加T
  def select(m1:T,m2:T): T ={
    if(m1.compareTo(m2)>0) m1 else  m2
  }
}

Note : Comparable[T] must be followed by a T

3. New main

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

    val u=new UpperBoundDemo[MissRight]
    val m1=new MissRight("biaozi",120)
    val m2=new MissRight("erdiao",999)
    val res=u.select(m1,m2)
    println(res.name)

  }
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324392953&siteId=291194637