The implict in Scala

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.