我的新博客地址:http://cuipengfei.me/blog/2013/12/23/desugar-scala-4/

Scala中有一个type关键字,用来给类型或者是操作起别名,用起来很是方便。

比如这样:

1
type People = List[Person]

这样就是给List[Person](方括号是Scala的类型参数的写法)声明了一个别名,叫做People。

接下来就可以这样使用它:

1
2
3
  def teenagers(people: People): People = {
people.filter(person => person.age < 20)
}

这个代码编译之后没有什么神奇的,仅仅是把所有出现People这个字眼的地方都用List of Person替代了。

1
2
3
4
5
6
7
  public List<Person> teenagers(List<Person> people)
{
return (List)people.filter(new AbstractFunction1() { public static final long serialVersionUID = 0L;
public final boolean apply(Person person) { return person.age() < 20; }
});
}

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

比如这样:

1
type PersonPredicate = Person => Boolean

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

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

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

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

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  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)
}
}

从一个人那里拿到钱,这种操作,我们称之为Tax。然后定义个税和苛捐杂税,或者也可以有任意多的税种。

然后就可以把任意的几个税种放在一个List里面,和calculateTax去composite了。

当然,没有type这个关键字,我们也可以composite functions。只不过就得写成这样:

1
2
val teenagerPred: (Person) => Boolean = person => person.age < 20
def incomeTax: (Person) => Double = person => person.income * 5 / 100

看着稍微有点眼花。

这种用type关键字给一种操作命名的代码反编译之后是这样的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  public Function1<Person, Object> teenagerPred()
{
return new AbstractFunction1() { public static final long serialVersionUID = 0L;
public final boolean apply(Person person) { return person.age() < 20; } } ;
}
public Function1<Person, Object> incomeTax()
{
return new AbstractFunction1() { public static final long serialVersionUID = 0L;
public final double apply(Person person) { return person.income() * 5 / 100; } } ;
}
public Function1<Person, Object> kejuanzaTax()
{
return new AbstractFunction1() { public static final long serialVersionUID = 0L;
public final double apply(Person person) { return person.income() * 20 / 100; } } ;
}

可以看到所有这种接受一个参数,返回一个值的操作都是Function1<Person, Object>。

推测一下,接受两个参数,返回一个值的是不是该叫做Function2呢?

1
2
3
type TwoToOne = (String, Int) => Double
def twoToOneImpl: TwoToOne = (str, i) => 1

反编译之后,果不其然:

1
2
3
4
public Function2<String, Object, Object> twoToOneImpl()
{
return new Hello..anonfun.twoToOneImpl.1(this);
}

那不接收参数,只有返回值的呢?

1
2
3
  type NoInJustOut = () => String
def noInJustOutImpl: NoInJustOut = () => "hello world"

反编译之后,其实是变成了Function0 of String:

1
2
3
4
  public Function0<String> noInJustOutImpl()
{
return new Hello..anonfun.noInJustOutImpl.1(this);
}

到这里,我们可以总结一下type alia这个糖衣:

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

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

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

1
2
3
4
5
6
7
8
  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

去掉Scala的糖衣(4) -- Type Aliase的更多相关文章

  1. 测试驱动 ASP.NET MVC Type Aliase

    Type Aliase 去掉Scala的糖衣(4) -- Type Aliase 我的新博客地址:http://cuipengfei.me/blog/2013/12/23/desugar-scala- ...

  2. 抹掉Scala的糖衣(14) -- Update Method

    欢迎关注我的新博客地址:http://cuipengfei.me/ 在Scala中,名字叫做update的方法是有特殊作用的. 比如: 1 2 3 val scores = new scala.col ...

  3. 除去Scala的糖衣(13) -- Default Parameter Value

    欢迎关注我的新博客地址:http://cuipengfei.me/ 好久没有写博客了,上一次更新竟然是一月份. 说工作忙都是借口,咋有空看美剧呢. 这半年荒废掉博客说到底就是懒,惯性的懒惰.写博客这事 ...

  4. scala中的self type

    scala目前的书籍有两<快学scala>和<scala编程>.资料确实不多,对这个语法使用只能结合使用进行理解. 先看源码: private[spark] trait Act ...

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

  6. [翻译]The Neophyte's Guide to Scala Part 12: Type Classes

    The Neophyte's Guide to Scala Part 12: Type Classes 过去的两周我们讨论了一些使我们保持DRY和灵活性的函数式编程技术,特别是函数组合,partial ...

  7. scala学习笔记(四)样本类与模式匹配

    访问修饰符 格式:private[x]或protected[x],x指某个所属包.类或单例对象,表示被修饰的类(或方法.单例对象),在X域中公开,在x域范围内都可以访问: private[包名]:在该 ...

  8. Spark基础-scala学习(一、入门)

    Scala解析器的使用 REPL:Read(取值)-> Evaluation(求值)-> Print(打印)->Loop(循环).scala解析器也被称为REPL,会快速编译scal ...

  9. Scala详解

    1       快速入门... 4 1.1             分号... 4 1.2             常变量声明... 4 1.2.1         val常量... 4 1.2.2  ...

随机推荐

  1. Tomcat 之 启动tomcat时 错误: 代理抛出异常 : java.rmi.server.ExportException: Port already in use: 1099;

    错误: 代理抛出异常 : java.rmi.server.ExportException: Port already in use: 1099; nested exception is:  java. ...

  2. &lt;LeetCode OJ&gt; 78 / 90 Subsets (I / II)

    Given a set of distinct integers, nums, return all possible subsets. Note: Elements in a subset must ...

  3. llinux环境变量查看和修改

    查看全局环境变量:env 查看所有环境变量:set 删除一个变量:unset [变量名] #只针对当前会话 设置一个变量:name=songjiankang export name #将这个变量提升为 ...

  4. JS中的转义字符

    http://www.cnblogs.com/wangpei/archive/2009/05/09/1453260.html \b        退格 \t          TAB,水平 \v    ...

  5. mysql允许远程连接

    GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY '123' WITH GRANT OPTION;

  6. 对C++对象内存模型造成的影响(类/对象的大小)

    首先重新回顾一下关于类/对象大小的计算原则: 类大小计算遵循结构体对齐原则 第一个数据成员放在offset为0的位置 其它成员对齐至min(sizeof(member),#pragma pack(n) ...

  7. c++,当const char*为0时,不能将其直接赋给string

    下面程序会崩溃: const char* t_objName = (obj!=NULL)?obj->getName(): 0; string objName=t_objName; cout< ...

  8. CentOS 7 下挂载NTFS文件系统并实行开机自动挂载

    CentOS 7 下想要挂载NTFS的文件系统该怎么办呢? 我们需要一个NTFS-3G工具,并编译它之后在mount就可以了,就这么简单. 首先要进入官网下载NTFS-3G工具 http://www. ...

  9. CentOS 5.4 安装和卸载桌面

    显示系统已经安装的组件,和可以安装的组件:#yum grouplist 如果系统安装之初采用最小化安装,没有安装xwindow,那么先安装:#yum groupinstall "X Wind ...

  10. python—networkx:在一张图中画出多个子图

    通过plt.subplot能够在一张图中画出多个子图 #coding: utf-8 #!/usr/bin/env python """ Draw a graph with ...