Scala Language Learning Generics (7)

Source: Internet
Author: User

==> generic class

---> T can represent any type

Class person[t]{Private var name:t = _ def setName (name:t) = {this.name = name} def getName (): T = {this.name}}//* * * * * * Test *****************object person{def main (args:array[string]): Unit = {var p = new Person[string] () P.setnam E ("Hello") println (P.getname ())}}


==> Generic Functions

---> Type parameters are placed after the method name

* Generic function//create a fixed type of array//normal function Def mkint (elems:int*) = Array[int] (elems:_*) def mkstring (str:string*) = "mkstring"//Using Generic functions , can receive any type Def Mkarray[t:classtag] (elems:t*) = Array[t] (elems:_*)//*********** test *****************// The normal function can only pass in the parameter of the relative type Mkint (mkstring) ("Hello", "world")//generic function can pass in any type of parameter Mkarray (11.26,665, +, "Hello")


Upper and lower bounds of the ==> type (Upper Bounds and Lower Bounds)

---> To define the scope of a generic variable:

---> s <: t (upper bound) s must be a subclass of type T or the class itself

class person1{  def gender ()  = {println (" Gender ")}}class man extends person1{  override def gender ()  = { println ("Man")}}class women extends person1{  override def gender ()  = &NBSP;{PRINTLN ("Women")} 
Object Upperboundsandlowerbounds {//defines a generic function that specifies the scope of the generic as an upper bound must be a subclass of Person1 or Person1 class, and call the gender method in the class Def getgender[t <: Person1] (g:t) = {G.gender ()} def main (args:array[string]): Unit = {//Create a Person1 object, call Getgender method call Persona  L Gender method var p:person1 = new Person1 Getgender (p)//Create a Man object, call Getgender method var in the man class by gender method m = new man Getgender (M)}}


< Span style= "Color:rgb (31, 73, 125); >u;: T ( Nether)         U  must be of type  T  parent class or The class itself, Here is no example, similar to the example above, just incoming   The parameter in the getgender  method must be   object of its parent class


==> View definition <%

---> is similar to the upper bounds of the type, but is more broadly applicable than the upper bounds of the type, except that all subclasses and classes themselves allow the type to be obtained through implicit conversions

def int2string[t <% String] (x:t, y:t) = {println (x + "* * * * *" + y)}//*********** test *****************int2string ("Hello" , "World") implicit def int2string1 (n:int): String = {n.tostring}int2string (100, 120)


==> Covariance and Contravariance

---> Covariance: The value of a generic variable can be a subclass or class itself with a "+" symbol subclass before the type parameter. c15> Convert to parent class

//*  covariance and contravariance     add  + to the front of the type to make the class's characteristics covariant//  Converting a subclass object to a parent class object is called covariant  +//  converting a parent class object to a subclass object is called an inversion  -package demo1{  //  parent class    class animal{}  //  sub-class   class bird extends animal  class  Sparrow extends Bird    //  What to eat        Covariant   class eatsomethings[+t] (t:t) {}  // *********** test *****************   object demo1{    def main (args:array[string]): Unit={       //  create an object to eat       var c1:eatsomethings[ Sparrow] = new eatsomethings[sparrow] (New sparrow)       var  c2:eatsomethings[animal] = c1    }  }} 


---> contravariance: The value of a generic variable can be the parent class or the class itself before the type parameter with a " - " symbol to convert the parent class to : omitting


==> Implicit conversion function

---> by keyword Implicit affirm

---> Single parameter

class fruit (name:string) {  def getfruitname (): String = {name}}class monkey (f:fruit) {  def say ()  = {println ("Monkey  like  " + f.getfruitname ())  }}// *********** test *****************object  Implicitdemo {  def main (args:array[string]): Unit = {    var  f:fruit = new fruit ("Bnanan")     //  call  fruit  method, hope  monkey this say  method to implement     //  need to convert  fruit  objects to  monkey  objects,   defines a stealth conversion function     implicit def fruit2monkey (f:fruit): monkey = {new  monkey (f)}     //  convert  fruit  objects to  Monkey  objects      //  call Monkey in the  say  Method     f.say ()   }} 


==> implicit parameters use the implicit keyword declaration of function arguments

---> You can use implicit arguments for type conversions

Implicit parameter def testparam (implicit name:string) = {println ("The value is" + name)}implicit val name:string = "This is an implicit value"//* * * * Test *****************testparam//---------------------------------------------------------------// Generic function with implicit parameter//ordered[t] Make type sortable,//prototype: def smaller//(implicit order:t = ordered[t]) def Smaller[t] (a:t, b:t) (Implicit order:t = ordered[t]) = if (Order (a) < b) A else b//*********** Test *****************smaller (+) smaller ("Hello", "HI")


==> implicitly class adds implicit-qualified classes to classes, and its main function is to enhance the function of the class.

---> Write an implicit class that enables the class to achieve more functionality

Object Testimplicit {//defines an implicit class implicit classes Calc (X:int) {def add (a:int): Int = a + x}//*********** test ********* def main (args:array[string]): Unit = {println ("two-digit and:" + 1.add (2)}}}

---> Program Process Analysis:

---when 1.add (2), Scala's compiler will not error, look in the current domain, there is no implicit decorated, you can use Int as the argument of the constructor, and have the Add method of the class, by looking, find the Calc

---Use implicit class Calc to execute the Add method


==> Personal Summary:

---> Through generics, allows us to define a mold, like a cake mold, we can separate into strawberries, blueberries and other raw materials to produce different flavors of cake to

---> by using the upper bound, nether, view definition, covariance, contravariance, to define the scope of the generics, so that we can pass in the parameters that conform to the rules

---> Implicit functions, implicit arguments, implicit classes, are first searched when the program is run, and if there are parameters, functions, and classes that conform to implicit, execute before running the program


If the summary is wrong, please also advise, thank you!!!


Scala Language Learning Generics (7)

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.