类型参数

  • 表现形式:在名称后面以方括号表示, Array[T]

  • 何处使用

    • class 中,用于定义变量、入参、返回值

      class Pair[T, S](val first: T, val second: S)
      // scala 可自动推断具体的类型
      val p = new Pair(42, "String") // Pair[Int, String]
    • 函数、方法

      def getMiddle[T](a: Array[T]) = a(a.length / 2)
  • 类型边界

    • 上边界 T <: UpperBound

      // 比较大小
      class Pair[T](val first: T, val second: T) {
      def smaller = if (first.compareTo(second) < 0) first else second
      }

      无法确定 first 是否存在 compareTo 方法,所以必须添加约束,fist 必须是 Comparable 的子类型,即需要添加上边界

      class Pair[T <: Comparable[T]](val first: T, val second: T) {
      def smaller = if (first.compareTo(second) < 0) first else second
      }
    • 下边界 T >: LowerBound

      // 替换第一个元素
      class Pair[T](val first: T, val second: T) {
      def replaceFirst(newFirst: T) = new Pair[T](newFirst, second)
      }

      替换第一个元素为 T 的父类 R,那么返回类型是什么? 如果需要返回 R,则需要添加约束,即需要下边界;否则返回的类型为 Any

      // 返回类型自动推断为 new Pair[R]
      def replaceFirst[R >: T](newFirst: R) = new Pair(newFirst, second)
    • 上下文边界 T : ContextBound

      Scala 2.8 对 Array 进行了更新优化,使用隐式转换和 manifest 将数组整合为 Scala 的集合库

      def tabulate[T](len: Int, f: Int => T)(implicitm: ClassManifest[T]) = {
      val xs = new Array[T](len)
      for(i <- 0 until len) xs(i) = f(i)
      xs
      } // 简化后
      def tabulate[T: ClassManifest](len: Int, f: Int => T) = {
      val xs = new Array[T](len)
      for(i <- 0 until len) xs(i) = f(i)
      xs
      }
      • ClassTag, 指定运行时的类型,如 Array[Int] 在运行时想指定为 int[]

        import scala.reflect._
        def makePair[T : ClassTag](first: T, second: T) = {
        val r = new Array[T](2); r(0) = first; r(1) = second; r
        } makePair(4, 9) // 实际调用
        makePair(4, 9)(classTag) // new 操作,即 ClassTag[Int] 构建原始类型数组 int[2]
        classTag.newArray
    • 多个边界

      • 可同时添加上界和下界 T >: Lower <: Upper
      • 不可添加多个上界或多个下届,但可实现多个 trait,
        • T <: Comparable[T] with Serializable with Cloneable
      • 可指定多个上下文边界 T : Ordering : ClassTag
  • 类型约束

    • 测试是否相等 T =:= U
    • 测试是否为子类 T <:< U
    • 测试是否可转换 T => U

    要添加该约束,需添加隐式参数

    // 约束类
    class Pair[T](val first: T, val second: T)(implicit ev: T <:< Comparable[T]) // 约束方法调用,只有类型满足才能调用成功,否则报错
    class Pair[T](val first: T, val second: T) {
    def smaller(implicit ev: T <:< Ordered[T]) =
    if (first < second) first else second
    } // 便于类型推断
    def firstLast[A, C <: Iterable[A]](it: C) = (it.head, it.last)
    // 无法推断类型 A
    firstLast(List(1, 2, 3)) // [Nothing, List[Int]]
    // 添加约束关系
    def firstLast[A, C](it: C)(implicit ev: C <:< Iterable[A]) = (it.head, it.last)

Scala Type Parameters 1的更多相关文章

  1. Scala Type Parameters 2

    类型关系 Scala 支持在泛型类上使用型变注释,用来表示复杂类型.组合类型的子类型关系间的相关性 协变 +T,变化方向相同,通常用在生产 假设 A extends T, 对于 Clazz[+T],则 ...

  2. Beginning Scala study note(8) Scala Type System

    1. Unified Type System Scala has a unified type system, enclosed by the type Any at the top of the h ...

  3. type parameters of <T>T cannot be determined; no unique maximal instance exists for type variable T with upper bounds int,java.lang.Object

    今天在进行代码检查的时候出现下面的异常: type parameters of <T>T cannot be determined; no unique maximal instance ...

  4. Java Error : type parameters of <T>T cannot be determined during Maven Install

    遇到了一个问题如下: Caused by the combination of generics and autoboxing. 这是由于泛型和自动装箱联合使用引起的. 可以查看以下两个回答:   1 ...

  5. learning scala type alise

    How to use type alias to name a Tuple2 pair into a domain type called CartItem type CartItem[Donut, ...

  6. learning scala repreated parameters

  7. Scala 深入浅出实战经典 第78讲:Type与Class实战详解

    王家林亲授<DT大数据梦工厂>大数据实战视频 Scala 深入浅出实战经典(1-87讲)完整视频.PPT.代码下载: 百度云盘:http://pan.baidu.com/s/1c0noOt ...

  8. scala类型系统 type关键字

    和c里的type有点像. scala里的类型,除了在定义class,trait,object时会产生类型,还可以通过type关键字来声明类型. type相当于声明一个类型别名: scala> t ...

  9. Scala Reflection - Mirrors,ClassTag,TypeTag and WeakTypeTag

    反射reflection是程序对自身的检查.验证甚至代码修改功能.反射可以通过它的Reify功能来实时自动构建生成静态的Scala实例如:类(class).方法(method).表达式(express ...

随机推荐

  1. Chrome headless三种安装方法

    在使用chrome headless的时候,使用安装源有很多的依赖问题,提供三种方法,最简单的是使用一键安装脚本. 1.添加chrome源来安装chrome 添加源: ## 添加:vim /etc/y ...

  2. uni-app项目记录

    1.如何定义一个全局属性 在App.vue 文件中,以 global.属性名= XXX; 定义 在其他页面就以 global.属性名来调用 或者在min.js 中使用 Vue.prototype 挂载 ...

  3. MySQL基础-Linux从入门到精通第十天(非原创)

    文章大纲 一.关于数据库二.MySQL的安装与初始化三.MySQL的基本操作(难点)四.扩展五.学习资料下载六.参考文章   一.关于数据库 mysql的基础知识,可以参考文章:https://www ...

  4. Spring项目配置多数据源

    项目中有用到多数据源,并进行动态切换,使用的是阿里的druid.看网上有一篇大致一样的就偷偷懒 import java.sql.SQLFeatureNotSupportedException; imp ...

  5. 【学习笔记】PYTHON网络爬虫与信息提取(北理工 嵩天)

    学习目的:掌握定向网络数据爬取和网页解析的基本能力the Website is the API- 1 python ide 文本ide:IDLE,Sublime    Text集成ide:Pychar ...

  6. Spring Boot集成Druid数据库连接池

    1. 前言 Druid数据库连接池由阿里巴巴开源,号称是java语言中最好的数据库连接池,是为监控而生的.Druid的官方地址是:https://github.com/alibaba/druid 通过 ...

  7. 国内不fq安装K8S四: 安装过程中遇到的问题和解决方法

    目录 4 安装过程中遇到的问题和解决方法 4.1 常见问题 4.2 常用的操作命令 4.3 比较好的博客 国内不fq安装K8S一: 安装docker 国内不fq安装K8S二: 安装kubernet 国 ...

  8. Python3和HTMLTestRunner生成html测试报告

    1.测试环境: Python3.5+unittest+HTMLTestRunner 2.下载HTMLTestRunner.py文件 下载地址 http://tungwaiyip.info/softwa ...

  9. python 数据库小测试

    1.整理博客 2.详细解释下列mysql执行语句的每个参数与参数值的含义 ​ mysql -hlocalhost -P3306 -uroot -proot # mysql (连接数据库) # hloc ...

  10. 03-docker入门-创建 docker 镜像

    方法1:从运行的容器创建方法2:编写 DockFile 文件创建 方法1: 打包镜像 docker commit -m "Test a change" 610 ubuntu:tes ...