隐式转换函数:
object test2 {
def main(args:Array[String]):Unit= {
repeat("abc",3)//把abc重复3次,然后打印出来
// repeat(123,3)//把abc重复3次,然后打印出来
reverse("htt")//自动翻转
// reverse(123)//自动翻转
}
//隐式转换函数
def repeat(str:String,n:Int):String={
var i=0
val sb=new StringBuffer(str.length*n)
while(i<n){
sb.append(str)
i+=1
}
sb.toString
}
//我们自己定义一个函数
implicit def int2String(i:Int) = i.toString;
implicit def int2String(i:Float) = i.toString;
implicit def int2String(i:Double) = i.toString;
//关键字implicit就是隐式的意思
//以上的函数只支持传进去一个String和int,但是当你传进去int和int是他就会报错,但是当你添加了implicat的关键字定义int转换String,那么他就会全局自动转换
//字符串翻转
def reverse(s:String)={
s.reverse
}
//隐式必须在当前作用域的范围之内
}
部分应用函数:
object test3 {
def main(args:Array[String]):Unit= {
deg(1);//返回值是6 ,只传入a的值
deg(10);//返回15 ,只传入a的值
}
//常规方法
def sum(a:Int,b:Int)={a+b}
def sum(a:Int,b:Int,c:Int)={a+b+c}
//他是一个函数,表示传入一个int类型,放回去一个int类型,sum方法的之传入一个参数,另外一个参数没有使用,没有定义
def deg :Int=>Int=sum(_,5)
val add=(c:Int) => sum(5,12,c)
}
咖喱函数:
object test4 {
def main(args:Array[String]):Unit= {
add5(10)//返回去15
}
//咖喱华函数,一个函数带有俩个参数列表
def sum(a:Int)(b:Int)={a+b}
//_表示把sum(5)生成的值传递出去
val add5=sum(5) _
//真真意义上的定义
def gas(a:Int,b:Int)={a+b}
//可以把上面的函数参数离散化
val curried=(gas _).curried
//代码咖喱华的作用
//分离参数
}
部分函数和分段函数
class test5 {
def main(args:Array[String]):Unit= {
f(3,3.0)//返回值6.0
}
//部分函数和分段函数
val f=new Function2[Int,Double,Double] {
def apply(a:Int,b:Double):Double=a+b
}
//这是一个函数对象
//部分函数对象
val fraction = new PartialFunction[Int,Int] {
def apply(d:Int)=42/d
def isDefinedAt(d: Int)=d!=0//检测函数是否有效,有效就调用,无效就不调用
}
//有一些函数可以接受一些参数
def fprint(p:PartialFunction[Int,Int])(a:Int)={
if(p.isDefinedAt(a)){
println(p(a))
}else{
println(s"$a is invalid")
}
}
}
高阶函数
object test6 {
def main(args:Array[String]):Unit= {
safeStringop("abc",reverse)
safeStringop("abc",upper)
}
//高级函数
def safeStringop(s:String,f:String => String)={
if(s!=null) f(s) else s
}
//翻转
def reverse(s:String)={s.reverse}
//变成大写
def upper(f:String)={f.toUpperCase}
}
递归和尾递归
object test7 {
def main(args:Array[String]):Unit= {
}
def whileLoop(cond: => Boolean)(body: =>Unit):Unit=if(cond){
body
whileLoop(cond)(body)
}
var i=10;
whileLoop(i>0){
println("aa"+i)
i-=1
}
class LoopUlessCond(body: =>Unit){
def unless(cond: =>Boolean)={
body
if(!cond) unless (cond)
}
}
var j=0;
loop{
println("aa"+j)
j-=1
}unless(j==0)
//递归不断压窄,不断出窄
def fab(n:Int):Int=if(n==0 || n==1) 1 else fab(n-1)+fab(n-2)
//
def fac(n:Int):Int=if(n==0) 1 else n*fac(n-1)
//
def fac(n:Int,accu:Int):Int=if(n<=1) accu else fac(i-1,i*accu)
//尾递归
@tailrec
def whileLoop(cond: => Boolean)(body: =>Unit):Unit=if(cond){
body
whileLoop(cond)(body)
}
class LoopUlessCond(body: =>Unit){
@tailrec
final def unless(cond: =>Boolean)={
body
if(!cond) unless (cond)
}
}
}