Scala类型参数Demo代码

package com.zjw.ch18

import scala.reflect.ClassTag

object Ch18Test extends App {
  /**
   * 泛型方法
   */
  def getMiddle[T](array: Array[T]): T = {
    array(array.length / 2)
  }
  println(getMiddle(Array(1, 2, 3, 4, 5, 6, 7)))

  /**
   * 类型变量上界界定
   */
  def compare1[T <: Comparable[T]](first: T, second: T): Int = {
    first.compareTo(second)
  }
   class Person4{
     def show(): Unit = {}
  }
  class Student4 extends Person4 {
    override def show(): Unit = {
      println("Hello I'm Student4 instance.")
    }
  }
  println(compare1("abc", "acb"))
  def showFunc[T <: Person4](instance: T): Unit = {
    instance.show()
  }
  showFunc(new Student4)

  /**
   * 类型变量下界界定
   */
  class Pair1[T](val first: T, val second: T) {
    def replaceFirst[R >: T](newFirst: R) = new Pair1[R](newFirst, second)
  }

  /**
   * 视图界定
   */
  def comapre2[T <% Comparable[T]](first: T, second: T): Int = {
    first.compareTo(second)
  }
  println(comapre2(4332, 345))

  /**
   * 上下文界定
   */
  def smaller[T: Ordering](first: T, second: T)(implicit ordering: Ordering[T]): T = {
    if (ordering.compare(first, second) < 0) {
      first
    } else {
      second
    }
  }
  println(s"smaller is: ${smaller(3,6)}")
  def signal[T : Ordering](a: T, b: T): Int = implicitly[Ordering[T]].compare(a, b)
  println(s"signal(0, 5) result is: ${signal(0, 5)}")

  /**
   * ClassTag上下文界定
   */
  def mkPairArray[T: ClassTag](first: T, second: T): Array[T] = {
    Array[T](first, second)
  }
  println(mkPairArray(2, 3).mkString(","))

  /**
   * T协变
   */
  class Animal1 {}
  class Bird1 extends Animal1 {}
  class Covariant[+T](t: T) {}
  val cov = new Covariant[Bird1](new Bird1)
  val cov2: Covariant[Animal1] = cov

  class Person3
  class Student3 extends Person3
  class Pair2[+T](val first: T, val second: T)
  def mkFriends(p: Pair2[Person3]): Unit = {
    println("Hello I'm covariant.")
  }
  val pairStudent: Pair2[Student3] = new Pair2(new Student3, new Student3)
  mkFriends(pairStudent)

  /**
   * T逆变
   */
  class Animal2 {}
  class Bird2 extends Animal2 {}
  class Contravariant[-T](t: T) {}
  val c: Contravariant[Animal2] = new Contravariant[Animal2](new Animal2)
  val c2: Contravariant[Bird2] = c

  trait Friend[-T] {
    def befriend(someone: T)
  }
  class Person2 extends Friend[Person2] {
    override def befriend(someone: Person2): Unit = {
      println("friend , I'm Person2")
    }
  }
  class Student2 extends Person2 {
    override def befriend(someone: Person2): Unit = {
      println("friend , I'm Student2")
    }
  }
  def mkFriendWith(s: Student2, f: Friend[Student2]): Unit = {
    f.befriend(s)
  }
  val susan = new Student2
  val fred = new Person2
  mkFriendWith(susan, fred)
}

展开阅读全文

没有更多推荐了,返回首页