scala详细笔记(十三)scala之泛型详解 您所在的位置:网站首页 泛型类可以带1个或多个类型参数吗 scala详细笔记(十三)scala之泛型详解

scala详细笔记(十三)scala之泛型详解

2023-07-04 22:44| 来源: 网络整理| 查看: 265

泛型用于指定方法或类可以接受任意类型参数,参数在实际使用时才被确定,泛型可以有效 地增强程序的适用性,使用泛型可以使得类或方法具有更强的通用性。泛型的典型应用场景 是集合及集合中的方法参数,可以说同 Java 一样,Scala 中泛型无处不在,具体可查看 Scala 的 API !

1 泛型类和泛型方法的定义  泛型类:指定类可以接受任意类型参数。

泛型方法:指定方法可以接受任意类型参数。

** * @Auther: 多易教育-行哥 * @Date: 2020/6/29 * @Description: 泛型类 * 将泛型的定义在类上 */ class Person[T, S](name: T, age: S) { def show(): Unit = { println(name) } /** * 泛型方法 在定义方法的时候指定泛型 * @param k * @param v * @tparam K * @tparam V */ def show2[K,V](k:K, v:V): Unit ={ println(k+"----"+v) } } object Test1 { def main(args: Array[String]): Unit = { val p = new Person[String, Int]("HANG", 23) p.show() p.show2[Int , Int](3,4) p.show2[String , Int](3+"",4) // 参数要写入泛型定义的指定的类型 } } 2 scala的变量界定

类型变量界定是指在泛型的基础上,对泛型的范围进行进一步的界定,从而缩小泛型的具体

class GenericTypeTest2 { def compare[T](first:T,second:T) = { if (first.compareTo(second)>0) first else second } } object GenericTypeTest2{ def main(args: Array[String]): Unit = { val tvb = new GenericTypeTest2 println (tvb.compare("A", "B")) } }

代码为什么编译不通过,是因为:泛型 T 并不一定具备 compareTo 方法 

class GenericTypeTest2 { def compare[T 0) first else second } } object GenericTypeTest2{ def main(args: Array[String]): Unit = { val tvb=new GenericTypeTest2 println (tvb.compare("A", "B")) } }

T



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

      专题文章
        CopyRight 2018-2019 实验室设备网 版权所有