scala进阶1-泛型

import scala.reflect.ClassTag

//定义带泛型的类
class Triple[F, S, T](val first: F, val second: S, val third: T)

object Test extends App{
  val triple = new Triple("Spark", 3, 3.14)
  val bigData = new Triple[String, String, Char]("spark", "hadoop", 'd')

  //定义带泛型的函数
  def getData[T](list: List[T]) = list(list.length / 2)
  println(getData(List("spark", "hadoop", "r")))

  //讲泛型函数传递给一个函数, 必须指定类型和_
  val f = getData[Int] _
  println(f(List(1, 2, 3, 4)))

  def biuldArray[T: ClassTag](len: Int) = new Array[T](len)
  println(biuldArray[Int](5).toList)

  //f的输入参数是A类型,产出是List[A], b必须是A类型
  def foo[A, B](f: A => List[A], b: A) = f(b)
}

你可能感兴趣的:(Scala)