存在类型

  • 形式: forSome { type ... }forSome { val ... }

  • 主要为了兼容 Java 的通配符

  • 示例

    Array[_]
    // 等价于
    Array[T] forSome { type T} Map[_, _]
    // 等价于
    Map[T, U] forSome { type T; type U <: T}

类型系统

类型 语法
Class/Trait class C, trait T
元组 (T1, T2...)
函数 (P1, P2...) => T
注解 T @A
参数类型 A[T1, T2...]
单例类型 value.type
类型投射 O#I
组合类型 T1 with T2 ...
中缀类型 T1 A T2
存在类型 T forSome { type/val... }

以上类型可在编写程序时定义,Scala 也有少量的类型在编译器内部使用

def square(x: Int) = x * x
// REPL 中返回的类型为
// square(x: Int) Int
// 省略的方法定义的 =>

自身类型 self type

  • 形式:this: Type =>

  • 用于限制 trait 只能被混编于指定类型的子类中

    trait T1 { def m1()}
    
    trait T2 extends T1 {
    this: Super1 with Super2 =>
    def m1() { methodInSuper() }
    } // 使用时只能在 Super1,Super2 的子类中混编 with T2
  • 引入的问题:自身类型不会自动继承,必须在子类中重复定义

    trait T3 extends T2 {
    this: Super1 with Super2 => // 必须重复定义
    }

依赖注入

  • 通过 trait 和 自身类型 实现简单的以来注入

    • 需要将所有的依赖都组合起来
    trait Logger { def log(msg: String) }
    
    trait Auth {
    this: Logger =>
    def login(id: String, password: String): Boolean
    } trait App {
    this: Logger with Auth =>
    // ...
    } object MyApp extends App with FileLogger("test.log") with MockAuth("users.txt")
  • 蛋糕模式 (cake pattern) 实现依赖注入

    • 依赖的组件使用自身类型来表示
    • trait 描述服务接口
    • val 定义需要实例化的服务
    • 层级化组合各个组件,在一个整体中注入需要的组件
    // 定义组件1
    trait LoggerComponent {
    // 描述接口
    trait Logger { ... }
    // 需要实例化的服务
    val logger: Logger
    // 接口具体实现
    class FileLogger(file: String) extends Logger { ... }
    ...
    } // 定义组件2
    trait AuthComponent {
    // 自身类型限定混编使用的类型
    this: LoggerComponent => // Gives access to logger
    // 定义服务接口
    trait Auth { ... }
    // 需要实例化的服务
    val auth: Auth
    // 接口具体实现
    class MockAuth(file: String) extends Auth { ... }
    ...
    }
    // 所有的依赖都集中在一处进行配置/注入
    object AppComponents extends LoggerComponent with AuthComponent {
    // 实例化服务/注入
    val logger = new FileLogger("test.log")
    val auth = new MockAuth("users.txt")
    }

    Scala编程的蛋糕模式和依赖注入

抽象类型

  • 形式: type Name

  • classtrait 中定义

  • 场景:具体类型需要在子类中确定

    trait Reader {
    type Contents
    def read(fileName: String): Contents
    }
    // 子类实现是具体确定类型
    class StringReader extends Reader {
    type Contents = String
    def read(fileName: String) = ...
    } class ImageReader extends Reader {
    type Contents = BufferedImage
    def read(fileName: String) = ...
    }
  • 抽象类型、类型参数的使用选择

    • 在类实例化时需要具体确认类型的场景使用类型参数,如 HashMap[String, Int]
    • 期望子类提供具体类型的场景使用抽象类型,如上例中的 Reader

Scala Types 2的更多相关文章

  1. Scala: Types of a higher kind

    One of the more powerful features Scala has is the ability to generically abstract across things tha ...

  2. Scala Types 1

    在 Scala 中所有值都有一种对应的类型 单例类型 形式:value.type,返回类型 value / null 场景1:链式API调用时的类型指定 class Super { def m1(t: ...

  3. 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 ...

  4. scala速成记录1

    选择  Learning Scala这本书,两百多页,足够薄. 安装 http://www.scala-lang.org/  下载Binary的版本.bin里边有所有操作系统下运行的可以运行的交互式s ...

  5. geotrellis使用(十九)spray-json框架介绍

    Geotrellis系列文章链接地址http://www.cnblogs.com/shoufengwei/p/5619419.html 目录 前言 spray-json简介 spray-json使用 ...

  6. Akka(33): Http:Marshalling,to Json

    Akka-http是一项系统集成工具.这主要依赖系统之间的数据交换功能.因为程序内数据表达形式与网上传输的数据格式是不相同的,所以需要对程序高级结构化的数据进行转换(marshalling or se ...

  7. 【原创】大叔问题定位分享(11)Spark中对大表子查询加limit为什么会报Broadcast超时错误

    当两个表需要join时,如果一个是大表,一个是小表,正常的map-reduce流程需要shuffle,这会导致大表数据在节点间网络传输,常见的优化方式是将小表读到内存中并广播到大表处理,避免shuff ...

  8. Spark SQL 函数全集

    org.apache.spark.sql.functions是一个Object,提供了约两百多个函数. 大部分函数与Hive的差不多. 除UDF函数,均可在spark-sql中直接使用. 经过impo ...

  9. org.apache.spark.sql.functions汇总

    测试数据: id,name,age,comment,date 1,lyy,28,"aaa bbb",20180102020325 scala> var data = spar ...

随机推荐

  1. Java基础之 集合体系结构(Collection、List、ArrayList、LinkedList、Vector)

    Java基础之 集合体系结构详细笔记(Collection.List.ArrayList.LinkedList.Vector) 集合是JavaSE的重要组成部分,其与数据结构的知识密切相联,集合体系就 ...

  2. access truncate

    access int access(const char *pathname, int mode); 确定文件或文件夹的访问权限 //unistd.h #define R_OK 4 /* Test f ...

  3. Linux 性能优化排查工具

    下图1为 Linux 性能优化排查工具的总结 图1 诊断 CPU 工具 查看 CPU 核数 总核数 = 物理CPU个数 X 每颗物理CPU的核数 总逻辑CPU数 = 物理CPU个数 X 每颗物理CPU ...

  4. liteos队列(五)

    1. 概述 队列又称消息队列,是一种常用于任务间通信的数据结构,实现了接收来自任务或中断的不固定长度的消息,并根据不同的接口选择传递消息是否存放在自己空间.任务能够从队列里面读取消息,当队列中的消息是 ...

  5. 很不错的python 机器学习资源

    http://www.cuijiahua.com/resource.html 曾看过的书,感觉一些很有用的学习资料,推荐给大家! Python基础: 网络教程推荐: 系统学习python3可以看廖雪峰 ...

  6. CentOS7创建启动脚本

    文件内容解释 [Unit]:服务的说明 Description:描述服务 After:描述服务类别 [Service]服务运行参数的设置 Type=forking是后台运行的形式 ExecStart为 ...

  7. yum总结

    yum企业案例          yum命令工具参数详解 yum install httpd 安装httpd软件包 yum search YUM搜索软件包 yum list httpd 显示指定程序包 ...

  8. android SDK安装Failed to fetch URL http://dl-ssl.google.com/android/repository/addons_list-1.xml出错 解决方案

    更换代理服务器:http://mirrors.neusoft.edu.cn 端口:80 reload 解决 若以上不成功在hosts文件中添加以下内容 #Google主页203.208.46.146 ...

  9. leetcode209. 长度最小的子数组

    双指针滑动窗口解法,时间复杂度O(N). 滑动窗口,想象一下,在一个坐标上存在两个指针begin 和i ,begin 代表滑窗的左边框,i代表滑窗的右边框.两者通过分别向右滑动,前者能使窗口之间的和减 ...

  10. spring cloud fegin传递request header

    本文链接:https://blog.csdn.net/zhongzunfa/article/details/82791903 1.概述 今天一个朋友, 遇到一个如何在使用spring cloud fe ...