当前位置: 首页 > news >正文

函数式编程与面向对象编程[4]:Scala的类型关联Type Alias

函数式编程与面向对象编程[4]:Scala的类型关联Type Alias


之剑 2016.5.4 23:55:19

<!--目录-->
<div id="category"></div>


类型关联 Type Alias

type关键字

scala里的类型,除了在定义class,trait,object时会产生类型,还可以通过type关键字来声明类型。

type相当于声明一个类型别名:

object TestMatrix extends App{  
  type IntList = List[Int]
  //接下来就可以这样使用它:
  type Matrix = List[IntList]

  val m = Matrix( IntList(1,2,3),
                  IntList(1,2,3),
                  IntList(1,2,3))
}
scala> type IntList=List[Int]
defined type alias IntList

这种给类型一个别名的特性只是一个小糖豆,不太甜,真正有趣的是给一类操作命名(联想C#中定义delegate)。

比如这样:


type PersonPredicate = Person => Boolean

接受一个Person,返回一个Boolean,我们把这一类用来判断一个人是否符合某个条件的操作统称为PersonPredicate。

然后我们可以定义以下predicate:

val teenagerPred: PersonPredicate = person => person.age < 20

然后前面写过的teenagers方法就可以这样重新定义:

  def teenagers(people: People): People = {
    people.filter(teenagerPred)
  }

按照这个思路下去,我们就可以开始composite functions了。比如说,我们跟人收税,就可以这么做:

    

  type Tax = Person => Double
  val incomeTax: Tax = person => person.income * 5 / 100
  val kejuanzaTax: Tax = person => person.income * 20 / 100
  def giveMeYourMoney(p: Person) = {
    calculateTax(p, List(incomeTax, kejuanzaTax))
  }
  def calculateTax(person: Person, taxes: List[Tax]): Double = {
    taxes.foldLeft(0d) {
      (acc, curTax) => acc + curTax(person)
    }
  }

总结一下type alia这个糖衣:

一个类型的type alias,类似于这样的:type t = x。编译器将在所有使用到t的地方把t替换为x。

对于一种操作的type alias,编译器将会根据参数列表和返回值类型的不同将其替换为对应的Function0,Function1,Function2 …… 一直到Function22。

如果我们真的定义一个超过22个参数的操作会如何呢?


  type twentyThree = (
      String, String, String, String,
      String, String, String, String,
      String, String, String, String,
      String, String, String, String,
      String, String, String, String,
      String, String, String
    ) => String
    

Scala编译器会直接告诉我们: type Function23 is not a member of package scala

结构类型

结构类型(structural type)为静态语言增加了部分动态特性,使得参数类型不再拘泥于某个已命名的类型,只要参数中包含结构中声明的方法或值即可。举例来说,java里对所有定义了close方法的抽象了一个Closable接口,然后再用Closable类型约束参数,而scala里可以不要求参数必须继承自Closable接口只需要包含close方法;如下:

scala> def free( res: {def close():Unit} ) { 
            res.close 
        }

scala> free(new { def close()=println("closed") })
closed

也可以通过type在定义类型时,将其声明为结构类型


scala> type X = { def close():Unit }
defined type alias X

scala> def free(res:X) = res.close

scala> free(new { def close()=println("closed") })
closed

上面传入参数时,都是传入一个实现close方法的匿名类,如果某个类/单例中实现了close方法,也可以直接传入


scala> object A { def close() {println("A closed")} }

scala> free(A)
A closed

scala> class R { def close()=print("ok") }

scala> val r = new R

scala> free(r)
ok

结构类型还可以用在稍微复杂一点的“复合类型”中,比如:


scala> trait X1; trait X2;

scala> def test(x: X1 with X2 { def close():Unit } ) = x.close

上面声明test方法参数的类型为:


X1 with X2 { def close():Unit }

表示参数需要符合特质X1和X2同时也要有定义close方法。

复合类型与with关键字


class A extends (B with C with D with E)

T1 with T2 with T3 …

这种形式的类型称为复合类型(compound type)或者也叫交集类型(intersection type)。

跟结构类型类似,可以在一个方法里声明类型参数时使用复合类型:


scala> trait X1; trait X2;

scala> def test(x: X1 with X2) = {println("ok")}
test: (x: X1 with X2)Unit

scala> test(new X1 with X2)
ok

scala> object A extends X1 with X2

scala> test(A)
ok

也可以通过 type 声明:



scala> type X = X1 with X2
defined type alias X

scala> def test(x:X) = println("OK")
test: (x: X)Unit

scala> class A extends X1 with X2

scala> val a = new A

scala> test(a)
OK


结构类型

结构类型:定义方法或者表达式时,要求传参具有某种行为,但又不想使用类,或者接口去限制,可以使用结构类型。


    class Structural { def open()=print("A class instance Opened") }

    object Structural__Type {

      def main(args: Array[String]){
        init(new { def open()=println("Opened") }) //创建了一个匿名对象,实现open方法
        type X = { def open():Unit } //将右边的表达式命名为一个别名
        def init(res:X) = res.open
        init(new { def open()=println("Opened again") })
        
        object A { def open() {println("A single object Opened")} } //创建的单例对象里面也必须实现open方法
        init(A)
        
        val structural = new Structural
        init(structural)
        
      }

      def init( res: {def open():Unit} ) { //要求传进来的res对象具有open方法,不限制类型
                res.open
            }
    }

Scala复合类型解析:





    trait Compound_Type1;
    trait Compound_Type2;
    class Compound_Type extends Compound_Type1 with Compound_Type2
    object Compound_Type {
      def compound_Type(x: Compound_Type1 with Compound_Type2) = {println("Compound Type in global method")} //限制参数x即是Type1的类型,也是Type2的类型
      def main(args: Array[String]) {
        
        compound_Type(new Compound_Type1 with Compound_Type2) //匿名方式,结果:Compound Type in global method
        object compound_Type_oject extends Compound_Type1 with Compound_Type2 //object继承方式,trait混入object对象中
        compound_Type(compound_Type_oject) //结果都一样,Compound Type in global method
        
        type compound_Type_Alias = Compound_Type1 with Compound_Type2 //定义一个type别名
        def compound_Type_Local(x:compound_Type_Alias) = println("Compound Type in local method") //使用type别名进行限制
        val compound_Type_Class = new Compound_Type
        compound_Type_Local(compound_Type_Class) //结果:Compound Type in local method
        
        type Scala = Compound_Type1 with Compound_Type2 { def init():Unit } //type别名限制即是Type1,也是Type2,同时还要实现init方法
      }

    }

Infix Type

Infix Type:中值类型,允许带有两个参数的类型。



    object Infix_Types {

      def main(args: Array[String]) {
        
        object Log { def >>:(data:String):Log.type = { println(data); Log } }
        "Hadoop" >>: "Spark" >>: Log //右结合,先打印出Spark,再打印出Hadoop
        
         val list = List()
         val newList = "A" :: "B" :: list //中值表达式
         println(newList)
        
        class Infix_Type[A,B] //中值类型是带有两个类型参数的类型
        val infix: Int Infix_Type String = null //此时A是Int,B为String,具体类型名写在两个类型中间
        val infix1: Infix_Type[Int, String] = null //和这种方式等价
        
        case class Cons(first:String,second:String) //中值类型
        val case_class = Cons("one", "two")
        case_class match { case "one" Cons "two" => println("Spark!!!") } //unapply
        
      }

    }


self-type




    class Self {
        self => //self是this别名
        val tmp="Scala"
        def foo = self.tmp + this.tmp
    }
    trait S1
    class S2 { this:S1 => } //限定:实例化S2时,必须混入S1类型
    class S3 extends S2 with S1
    class s4 {this:{def init():Unit} =>} //也能用于结构类型限定

    trait T { this:S1 => } //也能用于trait
    object S4 extends T with S1
    object Self_Types {

      def main(args: Array[String]) {
        class Outer { outer =>
         val v1 = "Spark"
         class Inner {
         println(outer.v1)  //使用外部类的属性
         }
        }
        val c = new S2 with S1 //实例化S2时必须混入S1类型
      }

    }




---


关于作者: 陈光剑,江苏东海人, 号行走江湖一剑客,字之剑。程序员,诗人, 作家

http://universsky.github.io/​


---

<link rel="stylesheet" href="http://yandex.st/highlightjs/6.2/styles/googlecode.min.css">
  
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="http://yandex.st/highlightjs/6.2/highlight.min.js"></script>
  
<script>hljs.initHighlightingOnLoad();</script>
<script type="text/javascript">
 $(document).ready(function(){
      $("h2,h3,h4,h5,h6").each(function(i,item){
        var tag = $(item).get(0).localName;
        $(item).attr("id","wow"+i);
        $("#category").append('<a class="new'+tag+'" href="#wow'+i+'">'+$(this).text()+'</a></br>');
        $(".newh2").css("margin-left",0);
        $(".newh3").css("margin-left",20);
        $(".newh4").css("margin-left",40);
        $(".newh5").css("margin-left",60);
        $(".newh6").css("margin-left",80);
      });
 });
</script>

相关文章:

  • windows下网管命令总结
  • Solaris10 安装
  • Mysql主从备份和SQL语句的备份
  • MapReduce分析明星微博数据
  • 在MVC中使用Json.Net序列化和反序列化Json对象
  • 统计分析工程的依赖项
  • Java使用SSLSocket通信
  • Open-E DSS V7 应用系列之一 系统简介
  • iOS开发之深复制和浅复制
  • 不要在要序列化的dto中随便写getter方法
  • 获取request和response
  • pfx证书与cer证书的区别
  • mysql互换表中两列数据方法
  • ASP.NET Core 指定环境发布(hosting environment)
  • [android] 手机卫士黑名单功能(ListView优化)
  • 分享的文章《人生如棋》
  • 「面试题」如何实现一个圣杯布局?
  • 【跃迁之路】【444天】程序员高效学习方法论探索系列(实验阶段201-2018.04.25)...
  • css系列之关于字体的事
  • Django 博客开发教程 8 - 博客文章详情页
  • Git 使用集
  • JavaScript 事件——“事件类型”中“HTML5事件”的注意要点
  • nginx(二):进阶配置介绍--rewrite用法,压缩,https虚拟主机等
  • 关键词挖掘技术哪家强(一)基于node.js技术开发一个关键字查询工具
  • 模仿 Go Sort 排序接口实现的自定义排序
  • 王永庆:技术创新改变教育未来
  • 问题之ssh中Host key verification failed的解决
  • 用jQuery怎么做到前后端分离
  • 智能合约Solidity教程-事件和日志(一)
  • 格斗健身潮牌24KiCK获近千万Pre-A轮融资,用户留存高达9个月 ...
  • (51单片机)第五章-A/D和D/A工作原理-A/D
  • (52)只出现一次的数字III
  • (C++)八皇后问题
  • (HAL库版)freeRTOS移植STMF103
  • (二)七种元启发算法(DBO、LO、SWO、COA、LSO、KOA、GRO)求解无人机路径规划MATLAB
  • (考研湖科大教书匠计算机网络)第一章概述-第五节1:计算机网络体系结构之分层思想和举例
  • (七)c52学习之旅-中断
  • (三)c52学习之旅-点亮LED灯
  • (十三)Flask之特殊装饰器详解
  • (详细版)Vary: Scaling up the Vision Vocabulary for Large Vision-Language Models
  • (转)IIS6 ASP 0251超过响应缓冲区限制错误的解决方法
  • (转)我也是一只IT小小鸟
  • (转)自己动手搭建Nginx+memcache+xdebug+php运行环境绿色版 For windows版
  • .jks文件(JAVA KeyStore)
  • .NET Remoting学习笔记(三)信道
  • .net 托管代码与非托管代码
  • .NET精简框架的“无法找到资源程序集”异常释疑
  • .NET企业级应用架构设计系列之结尾篇
  • .NET使用存储过程实现对数据库的增删改查
  • .pings勒索病毒的威胁:如何应对.pings勒索病毒的突袭?
  • @hook扩展分析
  • [ C++ ] STL_stack(栈)queue(队列)使用及其重要接口模拟实现
  • [ C++ ] STL---stack与queue
  • [2018-01-08] Python强化周的第一天
  • [C#]获取指定文件夹下的所有文件名(递归)