Scala implicit 隐式

隐式存在三种基本使用方式:
 

隐式参数

def calcTax(amount: Float)(implicit rate: Float): Float = amount * rate
implicit val currentTaxRate = 0.08F
//implicit val currentTaxRate2 = 0.18F // ambiguous implicit values
val tax = calcTax(50000F) // 4000.0
println(tax)

隐式地转换类型 

//todo val i: Int = 3.5 //直接报错
//加上这句:
implicit def double2Int(d: Double) = d.toInt
//再运行,没报错
val i: Int = 3.5 //i=3
println(i)

 隐式调用函数


class SwingType{
    def wantLearned(sw : String) = println("兔子已经学会了"+sw)
}
object swimming{
    implicit def learningType(s : AminalType) = new SwingType
}

class AminalType
object AminalType extends App{
    import implicits.ImplicitApp.swimming._ // 这里要加,不过不写会找不到wantLearned
    val rabbit = new AminalType
    rabbit.wantLearned("breaststroke") //蛙泳
}

一个典型的例子,来自scala官方文档 

abstract class Monoid[A] {
def add(x: A, y: A): A
def unit: A
}

object ImplicitTest {
    implicit val stringMonoid: Monoid[String] = new Monoid[String] {
        def add(x: String, y: String): String = x concat y
        def unit: String = ""
    }

    implicit val intMonoid: Monoid[Int] = new Monoid[Int] {
        def add(x: Int, y: Int): Int = x + y
        def unit: Int = 0
    }

    def sum[A](xs: List[A])(implicit m: Monoid[A]): A =
        if (xs.isEmpty) m.unit
        else m.add(xs.head, sum(xs.tail))

    def main(args: Array[String]): Unit = {
        println(sum(List(1, 2, 3))) // uses IntMonoid implicitly
        println(sum(List("a", "b", "c"))) // uses StringMonoid implicitly
    }
}

猜你喜欢

转载自blog.csdn.net/q503385724/article/details/88286367