scala implicit keyword

Implicit can be divided into:

  • Implicit parameter
  • Implicit conversion type
  • Implicitly call function

1. Implicit parameters

When we are defining a method, we can mark the last parameter list as implicit, indicating that the set of parameters are implicit parameters. A method can only have one implicit parameter list, which is placed in the last parameter list of the method. If the method has multiple implicit parameters, only one implicit modification is required. When calling a method that contains an implicit parameter, the compiler automatically fills in the appropriate value for the shuffled parameter if there is a suitable implicit value in the current context. If there is no compiler will throw an exception. Of course, we can also manually add a default value for the parameter marked as an implicit parameter. def foo(n: Int)(implicit t1: String, t2: Double = 3.14)

scala > def calcTax(amount: Float)(implicit rate: Float): Float = amount * rate
scala > implicit val currentTaxRate = 0.08F
scala > val tax = calcTax(50000F) // 4000.0

If the compiler does not find the second line of code in the context, it will report an error

2. Implicitly convert types

Converting a variable to the expected type using an implicit conversion is where the compiler first uses implicit. The rule is very simple, when the compiler sees type X but needs type Y, it looks in the current scope to see if there is an implicit definition from type X to type Y 
Example:

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

3. Implicitly calling functions

Implicitly calling a function can convert the object that calls the method, for example, but the compiler sees X.method, and the type X does not define a method (including base class) method, then the compiler looks for the type defined in the scope from X to other objects conversion, such as Y, and type Y defines a method method, the compiler first converts X to Y using implicit type conversion, and then calls the method of Y. 
example:

class SwingType{
  def  wantLearned(sw : String) = println("兔子已经学会了"+sw)
}
object swimming{
  implicit def learningType(s : AminalType) = new SwingType
}
class AminalType
object AminalType extends  App{
  import com.mobin.scala.Scalaimplicit.swimming._
  val rabbit = new AminalType
    rabbit.wantLearned("breaststroke")         //蛙泳
}

In the above example, the compiler finds that there is no wantLearning method on the object when the rabbit object is called. At this time, the compiler will look for an implicit view in the scope that can make it compile. After finding the learningType method, the compiler will pass the implicit view. The conversion converts the object into an object with this method, and then calls the wantLearning method

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325034752&siteId=291194637