---
title: "scala 函数"
author: "blackproof"
date: "2015-09-11T17:01:29Z"
tags: []
categories: ["编程语言"]
slug: "scala"
draft: false
lastmod: "2015-09-11T17:07:49Z"
id: 2242774
url: "https://blackproof.iteye.com/blog/2242774"
---

scala函数：

 

1.正常函数

```
  def normalReturn(x:Int,y:Int):Double ={
    return x*y*0.1;
  }
```

 

 2.没有返回值,不要等号，或是返回值为Unit

```
  def noRetrun():Unit = {
    println("1000")
  }
  def noRetrun2(x:Any) {
    println("no return")
    return x
  }
```

 

3 映射式定义 从int到double

```
  def f:Int=>Double = {
    case 1 => 0.1
    case 2 => 0.2
    case _ => 0.0
  }
```

 

 4.映射式定义  返回对象

```
  def f2:Option[User]=>User={
    case Some(x) => x
    case None => new User(1)
  }
```

 

5.映射式定义  多对一

```
  def mm:(Int,Int)=>Int = _+_;
  def mm2:Int=>Int = 30+_
```

 

 6.缺省函数

```
def join(a:List[String], s:String="-") = { a.mkString(s) }
```

 

7.变长参数 相当于java的...

```
  def sum22(ns: Int*) = {
    var s = 0
    for (n<-ns) s += n
    s
  }
```

    从左到右相减

```
def sum33(ns:Int*) = ns.reduceLeft(_-_)
```

 

8.函数参数  

```
 def somefunc(fuc:ClassDemo=>Boolean):Int={
    val funcre = fuc(new ClassDemo("zk","demo"))
    val result = if(funcre) 1 else 0
    result
  }
```

```
//函数参数，_是映射左边的参数，那个classDemo对象
    val r = somefunc ( _.getHost() > 10 )
    println(r)
```

 

9.slide写法，参数T

```
  def mylock[T](str:String)(func: => T):T={
    println(str)
    func
  }
```

  

```
    val r2=mylock("lock"){
      println("do some")
      1
    }
```

 

10.implicit函数，将引用本方法的类的String参数转为Long，（这里是为了科学计数法转换）

```
  implicit def typeConvertor(input:String):Long={
    var bd = BigDecimal(input)
    bd.toLongExact
  }
```

 

11.函数变量

```
var m = (x:Int,y:Int)=>x*y;
```

 

12.匿名函数

```
    //匿名函数（直接一个映射加上括号里的参数）
    println(((i:Int)=> i*i)(3))
    println(((j:Int,i:Double)=> i*j)(10,0.1))
```

 

13.偏函数   _ 用下划线代替1+个参数的函数

```
    val p0 = sum _ // 正确 
//    val p1 = sum(10,_,20) // 错误
    val p2 = sum(10,_:Int,_:Int) // 正确
    val p3 = sum(_:Int,100,_:Int)
    println(p0(1,2,3)) // 6
    println(p2(10,20)) // 130
    println(p3(10,1)) // 111
    
    println(((i:Int, j:Int) => i+j)(3, 4))
    println(((_:Int) + (_:Int))(3,4) )
```

 

 再加几个例子

函数参数

```
  def ffparam(x:Int, y:Int, m:(Int, Int)=>Int):Int={
    val x1 = x*10;
    val y1 = y*10;
    
    return m(x1,y1)
  }
```

 函数式，比较简单难懂

```
    val f1 = (n:Int) => 1 to 3 map (_*n) mkString " ";
    println(1 to 3 map f1 mkString "\n") //用f函数也可以，用f1也可以
```

 再来个Curry化

```
    
   println(sum(1)(3)) 
  def sum(a:Int)(b:Int) = { a + b } // sum(1)(2) = 3
```