1. As an implicit parameter
1 ObjectTest {2 3 def main (args:array[string]) {4 Import Fruitcolor._5Fruit.get ("Apple")6 }7 }8 9 Objectfruit{Ten def get (fruitname:string) (implicit fruitcolor:string): Unit ={ Oneprintln (S"$fruitName color is $fruitColor") A } - } - the Objectfruitcolor{ -ImplicitValcolor:string="Red" -}
2 Implict Class
Within the visual scope of a class, the primary constructor can be implicitly converted.
Limit: 1.implict class must be defined in Trait/class/object
2. There can be only one non-implicit parameter in the constructor
3. Within the scope of the Implict class, you cannot have method, member, and object of the same name.
Object main{ def Main (args:array[string]) { import helpers._ 5 times println (" Test") }}object helpers{ 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
Note: Implicit values cannot be in the top-level position and need to be used as a member
Objectmain{def Sum[a] (Xs:list[a]) (implicit m:monoid[a]): a={if(xs.isempty) M.unitElseM.add (Xs.head,sum (xs.tail))} implicitObjectIntmonoid extends monoid[int]{def add (x:int,y:int): Int=x+y def unit:int=0} implicitObjectStringmonoid extends monoid[string]{Overridedef unit:string ="" Overridedef 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 classsemigroup[a]{def Add (x:a,y:a): A}Abstract classMonoid[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
The implict in Scala