scala中的implict

 1.作为隐式参数

 1 object Test {

 2 

 3   def main(args: Array[String]) {

 4     import FruitColor._

 5     Fruit.get("apple")

 6   }

 7 }

 8 

 9 object Fruit{

10   def get(fruitName:String)(implicit fruitColor:String): Unit ={

11     println(s"$fruitName color is $fruitColor")

12   }

13 }

14 

15 object FruitColor{

16   implicit val color:String="red"

17 }

 2 implict class

   在类的可视范围内,主构造函数可以进行隐式转换。

   限制:1.implict class必须定义在trait/class/object中

           2.在构造函数中只能有一个非隐式的参数

           3.在implict class的视界范围内,不能有同名的method、member和object。

object Main{

  def main(args: Array[String]) {

    import Helpers._

    5 times println("test")

  }

}





object Helpers{

  implicit class IntWithTimes(x:Int){

    def times[A](f: => A): Unit ={

      def loop(current:Int): Unit ={

        if(current>0){

          f

          loop(current-1)

        }

      }

      loop(x)

    }

  }

}
View Code

3.implict object

  注意:隐式值不能在top-level的位置,需要作为一个member使用

object Main{



  def sum[A](xs:List[A])(implicit m:Monoid[A]):A={

    if(xs.isEmpty)m.unit

    else m.add(xs.head,sum(xs.tail))

  }



  implicit object IntMonoid extends Monoid[Int]{

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

    def unit:Int=0

  }



  implicit object StringMonoid extends Monoid[String]{

    override def unit:String = ""



    override def add(x: String, y: String): String = x concat y

  }



  def main(args: Array[String]) {

    println(sum(List(1,2,3)))

    println(sum(List("a","b","c")))

  }



}



abstract class SemiGroup[A]{

  def add(x:A,y:A):A

}

abstract class Monoid[A] extends SemiGroup[A]{

  def unit:A

}
View Code

 

 

 

Reference:

   1.http://docs.scala-lang.org/overviews/core/implicit-classes.html

   2.http://docs.scala-lang.org/tutorials/tour/implicit-parameters.html

 

你可能感兴趣的:(scala)