SHARE
TWEET

Local-Variable Type Inference in Java (var)

a guest Nov 14th, 2017 59 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import static java.lang.System.out;
  2.  
  3. /* Yuck! */
  4. class Gen { }
  5. class Gen1 <Gen> { }
  6. class Gen2 <Gen1, String> { }
  7. class Gen3 <Gen1, Gen2> { }
  8.  
  9. public class VAR {
  10.     public static void main (String[] args) {
  11.        
  12.         //Example #1
  13.         var one = "Type Inference!"; //Inferred to java.lang.String;
  14.         out.println("\nOur first use of var!:\t\"" + one + "\"");
  15.         out.println("The variable is of/can cast to type " +
  16.             ((Object)one).getClass().getName() + ".\n");
  17.  
  18.         //Example #2
  19.         var two = 9; //Inferred to int
  20.         out.println("\nOur second use of var!:\t\"" + two + "\"");
  21.         out.println("The variable is of/can cast to type " +
  22.             ((Object)two).getClass().getName() + ".\n");
  23.  
  24.         //Example #2
  25.         var three = 9.9; //Inferred to double
  26.         out.println("\nOur second use of var!:\t\"" + three + "\"");
  27.         out.println("The variable is of/can cast to type " +
  28.             ((Object)three).getClass().getName() + ".\n");
  29.  
  30.         //Example #4 - The evolution of messy generic instantiation
  31.         Gen3 <Gen1<Gen>, Gen2<Gen1,String>> gen3_1 = new Gen3 <Gen1<Gen>, Gen2<Gen1,String>> (); //88 Characters
  32.         Gen3 <Gen1<Gen>, Gen2<Gen1,String>> gen3_2 = new Gen3 <> (); //60 Characters
  33.         var gen3_3 = new Gen3 <Gen1<Gen>, Gen2<Gen1,String>> (); // 56 Characters
  34.         var four = new Gen3 <> (); //26 Characters
  35.         out.println("\nOur fourth use of var!:\t\"" + four + "\"");
  36.         out.println("The variable is of/can cast to type " +
  37.             ((Object)four).getClass().getName() + ".\n");
  38.         out.println("In Java 5-6 this generic code was 88 characters long.");
  39.         out.println("In Java 7-9 this generic code is 60 characters long.");
  40.         out.println("In Java 10 this generic code can be 26 characters long.\n");
  41.  
  42.         // #Example #5 - Common Collections
  43.         var five = new java.util.ArrayList<String> ();
  44.         five.add("Hello!");
  45.         five.add("Hiya!");
  46.         out.println("\nOur fifth use of var!:\t\"" + five + "\"");
  47.         out.println("The variable is of/can cast to type " +
  48.             ((Object)five).getClass().getName() + ".\n");
  49.     }
  50. }
RAW Paste Data
Top