您的位置:首页 > 编程语言

Scala操作笔记--函数式编程 及 case 类

2014-09-10 19:54 351 查看

1 咖喱函数

定义:多参数

def curriedSum(x: Int)(y: Int) = x + y

生成咖喱函数

scala> val onePlus = curriedSum(1)_

onePlus: (Int) => Int = <function>

2 使用递归完成参数可变的情况下加法

it("should sum all parameters by sum functions using variable length arguments") {

def add2(x: Int, y: Int) = x + y

def sum(arg: Int*): Int = {

if (arg.length <= 1)

arg(0)

else

add2(arg.head, sum(arg.tail: _*))

}

sum(2, 3) should be(5)

sum(2, 3, 4) should be(9)

}

3 函数多态

def matchedType[T](x:T) = {

x match {

case i:Int =>"int"

case f:Double =>"double"

case s:String =>"string"

}

}

4 case class

case class Calculator(val brand:String,val capacity:String) {}

几个便利性:

1 默认的构造函数,不用调用new

2 构造函数的参数默认有val功能

3 有默认的tostring等功能

因为有上述便利性,所以可以使用matcher来match对应对象,反而普通的class不能用来match,因为你不能match一个变量。

5 subclass什么时候要用override

1 如果父类是一个抽象的,在子类的实现不需要用关键字,实际上是实现。

2 如果父类是一个具体的方法,则子类的实现需要override,实际就是改写。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: