Slides that propose new features for future Java SE editions (9+). Includes proposals for language and JRE enhancements across multiple domains such as ease-of-use, reduced boilerplate, increased conciseness, improved concurrency and capability.
The goal is to make Java/JRE into a state-of-the-art platform for modern software development.
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Proposals for new function in Java SE 9 and beyond
1. Potential Java JSR Items
Community Input to Java SE 9+
Barry Feigenbaum, Ph.D.
barryfeigenbaum@gmail.com
10/20/2014
Java SE only; no Java EE items
2. Background
• Suggestions for inclusion into Java SE 9+
– Intended to be the basis for multiple JSRs
• See http://futurejava.wordpress.com for
discussion
3. Now, What Shall We Talk About?
• Way to much to cover in one session
– > 400 slides in this presentation alone
– 100s of pages of backing details (as draft JSRs)
• Goal is to peek interest in pursuing next steps
– Pruning/Defining/Authoring/Submitting JSRs
– Guiding JSRs through JCP
• JSR Committee
• Reference Implementation
• Technology Compatibility Kit
See https://www.jcp.org/en/jsr/proposal (may need to be JCP member to see this; free to sign up)
4. Expectations of Ya’All
1. Provide feedback
– On stated priorities
– On stated definition of items (alternate approaches)
– Potential implementation Gotchas/Flaws
2. Suggest items to add/remove from my catalog
– Likely many not thought of
– Items outside original scope (next slide)
– Prune lower value items
3. Signup to help make progress
5. Why these particular JSRs (in Brief)
1. ↓ Java Boilerplate/Learning Curve
– Continue trend of recent Java/JRE editions
– Automate several common idioms
2. ↓ JRE Inconsistencies
– Ex. size() vs. length() vs. getLength()
– Ex. differences between primitives and wrappers
3. ↑ Capability / Conciseness
– More competitive with C#, Groovy, Scala, etc.
• Yet backward compatible; minimal JVM hit
6. Presentation Content
• Three – Three – Three Presentations in One!
1. Briefs (title + 1ish examples)
Tonight’s content
2. Teasers (extended examples)
Better justification
3. Details (implementation info)
Read this before submitting critiques /
suggestions
7. Individual Items List
• ~ 80 suggested items
– Across multiple categories
– Development cost varies radically (from trivial to
man months)
• Item Catalog to follow…
– Will skip lower priority items due to time limits
– In no particular order
– Some overlap between items
– Some may have a history
BAF’s strawman priorities
Violet – Very High
Red – High
Yellow – Medium
Blue - Low
9. Major Item Category List
• Operator Overloading
• Import Enhancements/Aliases
• New Collection Types
• New Numeric Types **
• Parallel Processing Enhancements
• Reduced Boilerplate in Source
• Miscellaneous/Ease-of-Use Enhancements
Many items depend on each other for success
** make Java more viable for science/engineering (not just web apps)
10. Enhanced Auto-boxing
• Auto–box primitive on method call
– Significant move to equate primitives/wrappers
• Primitives need to exist only as dense form for arrays
– Allows many new operations on “primitives”
• Add methods to Boolean, Character, Number
subclasses
– Ex. int x = 1;
x.toHexString() new Integer(x).toHexString()
1.upto(10, x -> { System.out.println(x); })
11. Operator “Overloading”
• Map operators to methods (compiler)
– Operator methods are ordinary instance methods
• Can call; can be overloaded; select visibility; etc.
– Ex. a + b a.$plus(b) or b.$iplus(a) **
– Ex. a += 3 a.$aplus(3)
• Implement in many JRE classes
– Operator and conversion methods
– Collections, streams, numeric classes for sure
– Static Object.sameAs(Object x, Object y) vs. ==
** Operator method name syntax TBD. $xxx, _xxx_, etc.
12. Operator “Overloading”
• Overload-able Operators
– + - * / % ** ++ -- & | ^ ~ < <=
> >= == != ?= >> >>> << <<< [] []=
(…) (type) :: ==> <== ... >.. ..<
– :x x: (where “x” is + - * / % &
| ~ ^ < >)
• Ex. Using example type Foobar
– Foobar r, g, b, x = r + 2 * g + ++b;
– Foobar x = r.$plus(g.$imult(2)).$plus(b.$pinc());
implies new operator; italics implies new capability; :: may need to be :::
13. Example Implementation
• In BigInteger
– public BigInteger $plus(BigInteger other) =
this.add(other);
– public BigInteger $plus(String other) =
this + new BigInteger(other);
– public BigInteger $iplus(Integral other) =
new BigInteger(other.toString()) + this;
– public <T> T $cast(Class<T> type) =
(T)this.doubleValue();
Only a partial set, many more for full implementation
14. Code Safety Operators
• Safe Dereference (.?)
– Ex. anAddress.?city
anAddress != null ? anAddress.city **: null;
– Annotation/switch to make all “.” act like “.?”
• Safe Defaulted (?:) (AKA Elvis)
– Ex. int x = anInt ?: -1
int x = new Integer(anInt).ifTrue() ? anInt : -1;
– On any type implementing Truthful (ex. Number)
– Left == null is always false so right returned
**: must be reference type
15. Enhanced Concurrency
• Parallel For Loop
– Ex. parallelfor(var x: <iterable> {, Map}) { … }
– Exception/break ends all; continue ends current
– Need to synchronized/use atomic values
• Message Passing Actor Model
– Ex. {subject: “init”, data:”default”} ==> anActor;
– Loosely-coupled Actor-based message processing
– Hides most threading issues from users
16. Dynamic Extensions
• var/VAR declaration with static type inference
– Ex. var map = new HashMap<String, Integer>()
• Left-side generic type inference
– Ex. Map<> map = new HashMap<String, Integer>()
• @dynamic Object/Object[] (duck typing)
– Ex. @dynamic Object duck = new …
duck.quack(10); duck.die();
– Semantics based on use of reflection
17. Dynamic Extensions
• Method Literals
– Ex. var m = String.substring(int, int);
• Method Bindings (sync & async)
– var x = String.substring(int,it)::”Hello World!”;
– var hello = x(0,6); or x…0; var hello = x(6);
• Static Object.as (vs. instanceof) Type Testing
– Ex. Object o = ...; var p = as(Person.class, o)
Ex. var z = as(Integer.class, x, x -> { return x * 2; })
18. Dynamic Extensions
• SupportsPseudoMethods ** interface
– Allows receiver to support “virtual” methods
– Often implemented via switch on method name
– See teasers for an example
• Pseudo-implementation of interface
– “implements” clause not required
– Ex. void xxx(@conforms AnInterface x) {
x.aMethodInAnInterface();
}
– Parameter x can have any type with method
aMethodInAnInterface()
** suggest better name
19. New Collection Support
• Immutable (indexed) Tuple
– Ex. var t = (1, “Hello”, 4.1, new Date(), (1, ’a’));
– Ex. (var x, var y, var z) = (10, “hello!”, (-1, ‘c’));
• Immutable (Nil or head::tail) List
– Ex. var t = (1::(“Hello”::(4.1::(new Date()::Nil)))) ;
– Ex. var t = 1::“Hello”::4.1::new Date()::Nil
if “::” is right-associative operator
Use of “::” may be problematic so some other operator may be used.
20. New Collection Support
• Immutable (persistent) Map
– Ex. var t = (immutable) {“a”: 1, “c” 2};
t = (t[“b”] = 3);
– Smart copy on write
• Immutable (sequential/wrapper) Range
– Ex. var t = 0...99, u = 0..<100…2, v = start>..end
– Ex: var s1 = “123456”[1…5] “2345”
– Ex: var s2 = “123456”[-1…-5] “3456”
– Ex. var rx = (1,2,3, …, 100).asRange() == 1…100
21. New Collection Support
• Literals for List-like & Map types
– Ex. [1, 2, 3] ** ArrayList by default
– Ex. {a:1, b:2, c:3 } ** LinkedHashMap by default
– Nested list/map allowed
• Initializers for all List-like & Map types
– Ex. new Xlist() [1,2,3]; or new Xlist([1,2,3])
• New Collection Cast
– mutable immutable
** May need to use #[…] and #{…} syntax
22. New Numeric Support
• Immutable numeric Rational, Complex,
UnitValue (and Unit)
– Ex. var r = 5:/(long)7e12, c1 = 1e6 + 1.2e-3j,
c2 = 0.5 :< Pi / 2, kg = 1000 * gram;
• Mutable Dense N-Dimensional Matrix
– Ex. var t = Matrix.make(Integer.TYPE, 10, 10, 10)
– Bit, numbers, Boolean,
char, reference
23. New Numeric Support
• @checked (detect under/overflow) methods
– Ex. @check int shift(int x, int y) { return x << y; }
– Consider annotation/switch to disable shift size
restrictions
• Power (xy via **) operator
– Ex. var z = 2 ** 15; var sqrt = 101 ** 0.5;
• Literals for all (single part) numeric types
– Ex. BigInteger: 0x123456789abcdef00000000X
– Ex. BigDecimal: -123456789.987654321e400B
24. String Extensions
• Multi-line - ″ ″ ″ text that can span lines ″ ″ ″
• Raw - ″n not an escape″R (R|r)
• Specialized toString (debug & human forms)
– Can implements in parts
• Brief - `thisIsaString
• Interpolated - ~″${name} is ${age} old.″
• Executed – var outs = ~`ls *.out`
25. Aliases
• Create type aliases
– Ex. typealias List<String> as SList
– Ex. typealias String as string
• Create method aliases
– Ex. methodalias String.length(void) as size
• @alias methods
– Ex. @alias(“newName”) void oldName() { .. }
• @alias fields
– Ex. @alias(“x, y, z”) int _x;
26. Import Extensions
• Alias during import
– Ex. import java.util.StringBuffer as|add SB
• Terse Imports
– Ex. import java.swing.J* as *
– Ex. import java.swing.JFrame as f:JPanel as p
• Method/Block Nested Imports
– Ex. for(…) { import java.swing.*; … }
– Ex. import java.swing.* { … }
• Package imports
– Ex. import java.swing as s; s.JFrame f = new …
27. Method Parameter Extensions
• Defaulted Positional Parameters
– Ex. void xxx(int a, int b = 2, var c = 3L)
• Floating Named Parameters
– Ex. invoke(-1, -2, {“a”:1, ”b”:2, “c”;3})
– Ex. invoke(-1, -2, a:1, b:2, c:3)
– Ex. invoke(c:3, b:2, -1, a:1, -2)
– All named passed to last arg Map<String, Object>
• Reference (in+out) Parameters
– Ex: @ref int x = 1, y = 2; (may promote to Integer)
public void swap(@ref int a, @ref int b) {
int t = a; a = b; b = t;
}
– swap(x, y); x == 2, y == 1
28. Method Extensions
• Pseudo Instance Methods from Static
– Ex. “%s is %s!”.format(“John”, “bad”)
String.format(“%s is %s!”, “John”, “bad”)
• Full-Capture Values (AKA full Closures)
– Ex. @ref int x; … (a) -> { return a + ++x; }
– Value lives in heap (wrapped if needed)
• Terse (non-void) Methods
– Ex. int x; int getX() = x; int getX() = { result = x; }
29. Switch Extensions
• Use any type in Switch
– Ex. Class x = …; switch(x) { case String.class: … }
• Add “select” statement (switch w/auto break)
– Ex: select (x) { case 1: …; case 2: …; default: …; }
• Add multi-match: case x, y, x:
– Ex. select(x) { case 1, 2: …; case 3: …; }
• Add goto <case> (vs. break)
– Ex. case 1: …; break; case 2: … ; goto 1;
30. Text Enhancements
• Add basic XML support on Map<String, String>
contains List<XmlElement>
– Ex. var xml= XmlElement.parse(“””<data>
<v id=“x” value=“1” />… </data>”””);
• Add basic JSON support on Map<String, ?>
– Ex. var json = JsonObject.parse(“{ x: 1, y: 2, z: 3}”);
• Extend Appendable method set
– Ex. Appendable a = …;
a.appendln(“a”); a.appendf(“%d”, 10 * 20)
31. Enhanced Structure
• Services Model - Find/Manage/Update/
Dependency Injection
– Ex. See teasers for example
– Dynamic (in process) Service Location & Binding
• Duplicate Interface Method Implementation
– Ex. interface A { x(); } interface B { x(); }
class AB implements A, B {
x() { A.x(); }
A.x() { … }
B.x() { … }
}
32. Enhanced Structure
• @const References
– Ex. @const Person p = new Person();
p.name =“x”; compiler error
– Applies to use of p; not to Person
• @immutable Types
– Ex. @immutable class Xxx { public int x; }
Xxx i = ...; i.x = 1; compiler error
• @pure (cacheable) Methods
– Ex. @pure Object x() { … }
Object p = x(), q = x(), r= x(); assert(p == q == r);
33. Auto-Gen Boilerplate
• @autoc{onstruc}tor, @autostring, @autoequals,
@autocompare, @autosuper, @autoall
• Autosuper clones all superclass constructors
• Autoctor creates constructors for fields
• Autostring creates {human|debug}toString(),
• Autoequals creates equals() & hashCode()
• Autocompare adds Comparable/creates compareTo()
• Depend on @forctor, @fortostring, @forequals, etc.
– Ex. @autoall class C extends Q { @property int x, y, z; }
• @property fields
– Ex. @property(vetoable=true) String name;
– Creates missing accessors and event notifications
34. Auto-Gen Boilerplate
• @struct classes
– Ex. @struct class Person { String name; int age; }
• static top-level classes
– Ex. static class Utils { int func1() { .. }; … }
• @delegateto fields
– Ex. interface Y { void f2(); void f3(); }
class X implements Y {
void f1() {… }; void f2() { … } }
class A { @delegatesTo X x; void f3() { … } }
– A has f1(), f2(), f3() }; A implements Y
36. JRE Extensions
• Fluid Setters on all JRE classes
– Ex. X x = new X().xxx(1).yyy(2).zzz(3);
• Add large number of high use utility methods
– Ex. see teasers for example
– Minimize need for adding OSS for common tasks
– Fix many JRE self inconsistencies
• Compile time – Class.getCompileTime()
– Ex. var builtAt = new Date(
Main.class.getCompileTime());
37. Misc
• Broaden string usage via Stringy ** interface
– All CharSequence used where String used today
– Retrofit String Stingy declarations in JRE
• Defaulted Expressions
– Ex. Integer.parseInt(“bad value”) default -1;
• @partial classes
– 1+ source file per class
– Ex. see teasers for examples
• Package literals
– Ex. var utils = java.util.package;
** Stringy extends CharSequence
38. “C” Style Conditional Code
• @conditional (excludable) methods
– Ex. see teasers for examples
• #section <desc>/#endsection
– Ex. see teasers for examples
• #if/#else/#elif/#endif
– Ex. see teasers for examples
• #include sourceFile **
– Add source text verbatim (alt for partial classes)
** could be tricky for IDE to implement; Listings may be needed
41. Operator Overloading
• Allow most operators on any reference type
– as normal instance methods; compiler maps
operator to associated method call
– Left is instance: (ex. $plus, $or, …)
– Right is instance: (ex. $iplus, $ior, …)
– Augmented ?=, ++, --: ($aplus, $aor, …)
– ==, != require enablement (via annotation)
– >, >=, <, <= if type T is Comparable<T>
42. Operator Overloading…
• Supported Operators
– + - * / % ** ++ -- & | ^ ~ < <=
> >= == != ?= >> >>> << <<< [] []=
() :: ==> <== ... >.. ..< :x x:
(x is + - * / % & | ~ ^ < >)
• Ex. Using type Color
– Color r, g, b, x = r + 2 * g + ++b;
– Color x = r.$plus(g.$imult(2)).$plus(b.$pinc());
implies new operator; italics implies new capability
43. Operator Overloading…
• Enhanced conversions
1. If target type has constructor taking source type
2. If target type has static “from” or “fromXxx”
method taking Xxx source type
• Convert when
1. Upon explicit cast: Date d; d = (Date)aCalendar;
2. Upon initialization: Date d = aCalendar;
3. Assignment/comparison between Number types
44. Op Overloading - Strings
• Examples: String x, y, z
– x = y.concat(z); (or special compiler case x = y+z)
– x = y.repeat(3); (new, dup 3 times)
– x = y.repeat(-3); (new, reverse dup 3 times)
• Vs.
– x = y + z; (can drop special compiler support)
– x = y * 3; x = 3 * y;
– x = y * -3; x = -3 * y;
45. Op Overloading - Numbers
• Examples: BigInteger bi1 = ..., bi2 = …;
AtomicInteger a2 = …;
– BigInteger bi3 = bi1.add(bi2);
– a2.addAndGet(3);
– int x = a2.incrementAndGet();
• Vs:
– BigInteger bi3 = bi1 + bi2;
– a2 += 3;
– int x = ++a2;
46. Op Overloading - Numbers
• Examples:
– long fac(long x) {
if(x < 0)
throw new IllegalArgumentException();
if(x == 0)
return 1;
return x * fac(x – 1);
}
• }Vs:
– long fac(long x) {
if(x < 0) // auto promote to 0L
throw new IllegalArgumentException();
if(x == 0)
return 1; // auto promote to 1L
return x * fac(x - 1);
}
47. Op Overloading - Numbers
• Examples:
– BigInteger fac(BigInteger x) {
int rel = x.compareTo(BigInteger.ZERO);
if(rel < 0)
throw new IllegalArgumentException();
if(rel == 0)
return new BigInteger.ONE;
return x.multiply(fac(x.subtract(BigInteger.ONE));
}
• }Vs:
– BigInteger fac(BigInteger x) {
if(x < 0) // auto promote to 0X
throw new IllegalArgumentException();
if(x == 0)
return 1; // auto promote to 1X
return x * fac(x - 1);
}
53. Op Overloading - Much Potential
• Example: Possible CharSequence (covers all
implementations) overloaded operators
– Compile RE: ~”...”; Match RE: “…” ~= “…”;
– Concat: “…”+”…”;
– Repeat: “…”*n (reverse if <0); “…”*0 == “”
– Remove: “….”-”…”
– Substring: “…”[x..<y]; CharAt: “...”[n]
– Replace: “…”[m...n] = “…” (remove if “”)
– Append: “…”<<“…”; Prepend: “…”>>“…”;
• Above tip of iceberg
54. Declaration Type Inference
• Java supports right-side generics inference today
– Map<String, Integer> x = new HashMap<>();
• Add left-side inference
• Map<> x = new HashMap<String, Integer>();
• Generics on either side should be sufficient
• Example:
– Map<> snmap = { "one":1, "two":2, "three":3.0 };
– Is interpreted as:
– Map<String, ? extends Number> snmap =
– { "one":1, "two":2, "three":3.0 };
55. Var Type
• Individual declarations:
– Integer ten = new Integer(10);
– int twenty = 20;
– long ninety = 90;
– String name = "Barry“;
– double y = 30.5;
– LinkedList<> stringList1 = new LinkedList<String>();
– Number x = new Integer(20);
– List<String> stringList2 = new LinkedList<String>();
56. Var Type…
• Can become simplier:
– var ten = new Integer(10),
twenty = 20,
ninety = 90L,
name = "Barry“,
y = 30.5,
stringList1 = new LinkedList<String>();
– Number x = new Integer(20);
– List<String> stringList2 = new LinkedList<String>();
Consider using VAR that makes primitive into wrapper type.
Unlike in JavaScript var type is static per identifier
57. Collection Initialization
• Arrays support initialization:
– Example:
• new Object[] { 1, 2, 3 }
• Collections should also:
– Examples:
• new ArrayList() { 1, 2, 3 };
• new HashMap() { 1:”one”, 2:”two”, 3:”three” };
Collection implements new interface: Initable<T> with initAll(T[]|Collection<T>)
58. Immutable Tuple Type
• Examples:
• (); (1,) // empty; 1 Integer
• (1,2,3.0) or (1,2,3.0,) // 3 Numbers
• ("hello", "World!") // 2 Strings
• (1, "World!") // 2 Objects
• ((1,2),('a','z')) // 2 Tuple<? extends Object>
• (var x, var y, var z) = (1, 2.0, “Three”)
Syntax possibly: #( <value>,…)
Not fixed size so therefore non Generic; like immutable ArrayList
59. Immutable List Type
• Examples:
– List<Integer> li = 1::(2::(3::(4::Lists.Nil))));
– List<?> lx = 1::(2.0::(”Three”::
((4::Lists.Nil)::(”Five”::Lists.Nil))::Lists.Nil));
“::” for example, other operators possible: ex. +:, :+, +
Note: if “::” right-assocative then
List<Integer> li = 1::2::3::4::Lists.Nil;
60. Immutable Map Type
• Like standard Map interface except:
– put() & putAll() return the Map instance
• Recommend putAll over put for multiple values
– remove() returns the Map instance
• Implementations
– Optimize update/replacement
• In general only hash bucket lists need to be changed
61. Immutable Range Type
• Examples:
– 0 to 9: 0 ..< 10 (or 0..<10…1); 9 to 0: 10>..0…-1
– 0 to 10: 0 … 10; 10 to 0: 10…0…-1
– Odds: 1…100...1; Evens: 0…100…1
– Calc steps : 1…Long.MAX_LONG…(x -> x * x)
– Characters: ‘a’…’z’ (‘a’, ‘b’, … ‘y’, ‘z’)
– Strings: “aa”…”zz” (“aa”, “ab”, … “zy”, “zz”)
– Empty: 0..<0 (many other alternatives,
Ranges.EMPTY)
62. Immutable Range Type…
• Examples:
– Over array: Ranges.make(new int[] {1,2,3})
– Or: Ranges.make(1,2,3);
– Over collection: Ranges.make(aList)
– Or: aList.asRange() (takes static snapshot)
– Variable, non int: double x, y, z: x…y…z
– assert 1..100 < 1…1000
– assert 1…100…1 > 1…100…2
Assume “==“ overloaded to equals(); < to compareTo()
63. Immutable Range Type…
• Examples:
– for(int i: 0..<100) {
:
}
– for(1…n) {
:
}
If index not needed
Assume “==“ overloaded to equals(); < to compareTo()
Enhanced for syntax
64. Range as Index
• Examples:
– “0123456789”[1…3] == “123”
– “0123456789”[-1…-3] == “987”
– “0123456789”[-3…-1] == “789”
Assume “==“ overloaded to equals(); “[]“ overloaded
65. Immutable Rational Type
• Examples:
– int x = 1, y = 2, z = 20, a = 21, b = 11, zero=0,
num1 = 21:/5, num2 = 5:/3;
– Rational r1 = x:/y; // 1:/2 (also 1 :/ 2)
– Rational r2 = z:/y; // 10:/1
– Rational r3 = (2*x):/-y; // -1:/1 ==
-Rationals.ONE
– Rational r4 = (50*-y):/z; // -5/1
– Rational r5 = a:/b; // 21:/11
Note: Could use
instead of :/ for
rational divide
Consider adding (long) rational primitive type ; compiler only (2 int/long) – no JVM change
69. Immutable UnitValue Type
• Prevent Apples + Oranges errors
• Units define “units” (ex. Newton, Hertz, Gram)
– Custom or JRE provided
• UnitValues are Numbers with an associated
Unit
– Ex. IntegerUnitValue extends Integer **
– Can +,- only compatible
– Can *,/,** any
Requires non-final Integer or new nonpackagefinal
70. Immutable UnitValue Type…
• Examples:
– Unit newton = ...; meter = ...; second = ...;
– UnitValue newton100 = 100 * newton;
– Integer newton100asInteger = newton100;
– Integer unitVelocity = 1 * (meter / second);
– UnitValue m = 1000 * gram;
– UnitValue e = m * C ** 2; // or = m * C * C;
– UnitValue x = 1000 * second;
– Number y = e + x; // Exception
– Number z = e * x; // OK
71. Packed Matrix Type
• 3-dimensional [N, M, L] Matrix example
– N * M * L cells
• View on Matrix
• View on View
• Can also view as
array
(1 dimension
N * M * L long)
• Can update through
view
• Bit, primitive, ref
Ignore labels
From http://www.altera.com/technology/system-design/articles/2013/scanned-radar-signal-processing.html
72. Matrix Access
• Whole Matrix and View (AKA sub-range)
• Picture shows
possible
additional options
(stride, selection,
partition, etc.)
• Do provide transforms
like flip and transpose
http://incanter.org/docs/parallelcolt/api/cern/colt/matrix/doc-files/slice.gif
73. Potential Functionality
• Get and set the cell @ index
• Get rank and shape
• Apply Math.* operations to all elements using lambdas
• Operations to transpose, inverse, etc.
• For liked shaped:
– Standard operations (ex. +, -, *, /)
– CompareTo elements (produce array of ints)
• Reduction functions (sum, min/max value, etc.) using
lambdas
• (Consider) array construction functions (merge, pack,
spread, unpack)
• Parallel operation variants where no cross-cell contention
74. Checked Arithmetic
• Examples: All generate exceptions
assume all in @checked(overflow=true,
underflow=true) method
– int x = 1; x << 50 - overflow (needs BigInteger)
– Int x = 1024 >> 10 - underflow (result is double)
– Int x = 0x7FFFFFFF + 1 – overflow (sign change)
– int x = (int)1FFFFFFFFL – overflow (sig bits lost)
– Short s = (short)(65 * 1024) - ditto
75. Literals for all Number Types
• Add More literals:
– BigInteger: 100000…0000000X (or x)
– BigDecimal: 100000000000.00000B (or b)
• Allow “_” between digits
• Some types have constant expressions instead
of literals
– Rational type: 1 :/ 2
– Complex type: 10+3j; 10 @ Math.PI / 2
76. Power Operator
• Allow xy to be expressed as an operator (vs.
function) x ** y
– New right-associative binary “**” (AKA
$power/$starstar ) operator
• Add similar Java/JRE support as * (multiply)
has; on all numeric types (primitive and Big)
• Example:
– long x = 2**45; double y = Math.PI**-3.5**2
Assume “**” overloaded; Suggest creating BigMath class like Math class
77. “As” Type Testing
• Example:
• String s = “…”; Object o = new Integer(5);
• assert as(String.class, s) == s;
• assert as(Integer.class, s) == null;
• assert as(Integer.TYPE, s) == null;
• assert as(Integer[].class, o) == o;
• as(Integer[].class, o,
n -> System.out.printf(
“%d%n”, n[0]) );
static <T> Object.as(T type, Object v, { lambda })
Interface Castable<T>; T castTo(Class<T>)
78. Safe Dereference Operator
• Shorten common Java idiom
– x != null ? x.y : null
• Can cascade: (ex. x.?y.?z)
• Ex.
– String city= user?.address.?city
• Vs:
– String city = (user != null ?(user.address != null ?
(user.address.city) : null) : null)
• Add @autosafe class/method annotation
– Converts use of “.” to “.?”
79. Default Operator
• Shorten common Java idiom
– x ? x : y;
• Default (Elvis): x ?: y
– Short for: isTrue(x) ? x : y
– Uses Java truth (!null, !0, !false); returns x if It is
“true”, else y
• Add HasTruth interface for reference types
– If implemented; use its isTrue() method**
– Ex. String.isTrue() = length() > 0;
– Ex. Integer.isTrue() = intValue() != 0;
**: Operators && and || also do this
80. Import Aliases
• Examples:
– import java.sql.SQLException as SqlException
– import java.util.List as ValueList
– import java.awt.List as SelectList
– import javax.swing.JButton as Button
– import SomeInterface as ISomeInterface
– import SomeInterfaceImpl as SomeInterface
– import static Math.sin add sine
81. Terse Imports
• Examples:
– import java.swing. JTable:JPanel:JButton
– import java.swing. JTable as Table:
JPanel as Panel, Pane: JButton as Button
– import javax.swing.J* as *
– import xxx.yyy.I?*Service as ?*Service
82. Package Imports
• Examples:
– import java.awt as awt
– import java.util as u
assert java.util.package == u.package
then
– u.List items = new u.ArrayList()
– awt.List select = new awt.List()
84. Type Aliases
• Examples:
– typealias java.util.StringBuilder as SB
assert StringBuilder.class == SB.class
– typealias String as string
– typealias String[] as strings
– typealias java.math.BigDecimal as decimal
– Typealias boolean as bool
– typealias java.sql.SQLException as SqlException
– typealias HashMap<? Extends CharSequence, ?
Extends CharSequence> as SeqToSeqMap
85. Method Aliases
• Examples:
– methodalias String.toString(void) as asString
– methodalias String.length(void) as size
– methodalias StringBuilder.getLength(void) as size
– methodalias StringBuilder.append(…) as add
– methodalias <K extends String, V extends
Number> Map<K, V>.put(K, V) as putNumber
86. Field “Aliases” by Annotation
• Leverage JavaBeans
• Auto-generation of access methods
• @alias(“x, y, z”) private int xxx
– Perhaps @alias(“x, y, z, xxx”) private int _xxx
87. Method “Aliases” by Annotation
• Auto-generation of methods
• Visibility same as base method
• @alias(“pqr, lmn”) public int xyz() { … }
• @Deprecated only effects base method
88. Map/List Literals
• Java has array literals, it needs to add literals
for common collections
• List literal: [ <value>,… ]
• Map Literal : { <key>:<value>, … }
• Type is least common sub-type of key/value
• Literals can be passed to constructors to set
type (or cast to type)
– new ArrayList([1,2,3]) or (TreeMap){1:x,2:y,3:z}
May need to use #[…] and #{…} format
90. Method Bindings
• Example:
– String s = ...;
Binding** substring =
Bindings.bind(String.substring(int, int), s);
-- or –
Binding substring = String.substring(int, int)::s;
:
String s2 = substring(0, 10);
** an interface with at least one implementation
91. Method Bindings…
• Example:
– MyIOService s = …;
var copy = MyIOService.
copyTree(File, File)::s
…new File(“.”)
…new File(“elsewhere”)
.async(true);
– var f = copy();
: do other stuff
int rc = f.get();
Call operator
Same as
copy.$call()
92. Add “Chaining” Setter
• For field “<type> xxx” JavaBeans defines
access methods as:
– <type> get/isXxx() { return xxx; }
– void setXxx(<type> v) { xxx = v; }
• Add new setter:
– <thisType> xxx(<type> v) { xxx = v; return this; }
• This allows “fluent” assignments like:
– Xxx xxx = new Xxx().aaa(1).bbb(3).ccc(3);
• Retrofit into all JRE classes
93. Pseudo Instance Methods
• Examples:
– Class X has no doThis/doThat methods
• These calls:
• X x = new …
• x.doThis(1, 2, 3)
• x.doThat(3, 2, 1)
• Becomes:
• SomeUtilClass.doThis(x, 1, 2, 3)
• SomeUtilClass.doThat(x, 3, 2, 1)
Must be unique match across imported (vs. all) classes; else need marker annotation on
subject methods
94. Pseudo Instance Methods…
• Examples: Based on String class
• This call (previously invalid):
– String x = “%s %s %s”.format(“x”, “y” “z”);
• Now succeeds (is mapped to):
• String x =
String.format(“% s %s %s”, “x”, “y” “z”);
• Only if no real instance method matching format(…)
95. Pseudo Methods
• Assume class Expando implements (new)
SupportsPseudoMethods** interface
• Assume Expando class has methods:
– normalMethod1(), normalMethod2() and
onMethodCall()
• onMethodCall has cases for:
– nowDate(), nowMillis() and other()
** suggest better name
96. Pseudo Methods…
• Example:
– Expando e = new Expando();
// only real method
e.normalMethod1();
// called via redirection
Date d = (Date)e.nowDate();
long seconds = (Long)e.nowMillis();
e.other();
e.xxx();
• All the above statements compile, but the xxx()
call fails at run time with a MethodNotFound-
Exception.
97. Dynamic Variables
• Examples:
– @dynamic Object duck = new Duck();
– duck.quack();
– double weight = (Double)duck.getWeight();
• Compiles OK; quack() and getWeight() work if
defined in Duck (or superclass), else runtime
MethodNotFoundException occurs
Simple implementation uses reflection; better invokedynamic
98. String Enhancements
• Simple (JavaIdCharacter content only):
`this_is_a_string (makes great hash key)
• Long Strings:
“”” any text here, including “ and ‘ and n and
line ends until the next “””
• Raw Strings (ignore ‘’ as escape):
– “this n is not an escape”R (or r)
– Also “”” … “””r
99. String Enhancements…
• Smart Strings:
~“””${name} is
${age > 50 ? ”old” : “young” }””” **
– Simple id reference can be shortened: $name
• Causes any ${<expr>} to be replaced by the value
of the <expr> evaluated in current context
– May cause internal Map to be sent to interpolate()
with all (perhaps just referenced in expr) variables in
current context.
**: overloaded operator does “interpolate()” (ah la Perl/Groovy) behavior
100. String Enhancements…
• Unified StringBuilder/Buffer and String
– Create new Interface Stringy that covers all String
instance methods
– Make StringBuilder/Buffer implement Stringy
• So they can be used most places Strings are
• Replace most JRE methods String parameters/results
with Stringy type
– The compiler will treat Stringy items as String (ex.
x + y)
Stringy extends CharSequence
101. Defaulted Positional Parameters
• Ex. public int xxx(int a, int b = 2, long c = 3) { … }
• Generates methods:
– public int xxx(int a, int b, long c) { … }
– public int xxx(int a, int b) { return xxx(a, b, 3); }
– public int xxx(int a) { return xxx(a, 2, 3); }
• Cannot combine with … parameters
• Fails if ambiguous methods generated
• Allows: public int xxx(int a, var b = 2, var c = 3L) …
Distinct overloaded methods; not call site injection
102. “Keyword” Parameters
• Example:
– // Xxx(Map<String,Integer> params)
– Xxx xxx = new Xxx({"x":1, "y":2, "z":3}); or just
– Xxx xxx = new Xxx("x":1, "y":2, "z":3);
• More generally:
– // Xxx(int x, int y, Map<String,Integer> params)
– Xxx xxx = new Xxx(1, 5, `x: 1, `y: 2, `z: 3); key order not
– Xxx xxx = new Xxx(1, `x: 1, `y: 2, `z: 3, 5); important
– Xxx xxx = new Xxx(`z: 3, `y: 2, `x: 1, 1, 5);
• If the key consists only of Java Id
– Xxx xxx = new Xxx(z: 3, 1, y: 2, x: 1, 5); no quoting needed
– Xxx xxx = new Xxx(z: 3, 1, (y): 2, x: 1, 5); fails, must be const
Only works if last parameter is Map<String,?>
103. Reference Parameters
• Given:
public <T> static void swap(
@ref T a, @ref T b) {
T t = a; a = b; b = t;
}
• Ex:
@ref int v1 = 3**, v2 = 5;
:
swap(v1, v2);
assert v1 == 5 && v2 == 3;
** could be internally: Wrapper<Integer> v1 = new Wrapper(3), …
104. Specialized toString
• Add debugToSting() & humanToString()
• Ex:
public String debugToString() {
StringBuilder sb = new ..;
$debugPrefix(sb); getClass.getName
$debugBodyStart(sb); “[“
$debugBody(sb); “”
$debugBodyEnd(sb); “]”
$debugSuffix(sb); “@”+System._HashCode
return sb.toString();
}
• Allows subclasses opportunity to override minimally (ex. override
$debugBody() only)
toString() can call either or neither at its discretion;
Object.toString() { return debugToString(); }
105. Enhanced Switch
• Allow “goto” case instead of break
• Class z = new ….;
switch(z) {
case String.class:
:
break;
case Xxxx.class:
case Number.class:
:
goto String.class;
}
Consider “select” statement; same as “switch” with auto “break” between cases.
Consider allowing syntax: case x, y, z:
106. Enhanced Switch…
• Add new interface Case with method
boolean matches(Object other)
• Switch can test any type implementing Case
– Use if/else If/else implementation
– Implement Case on (at least) any JRE Comparable
class and enums
– Consider adding Object method matches() so all types
can be used in switch (thus no Case interface needed);
defaults to calling equals()
• Can eliminate special String/enum support
• More readable than if/else if/else sequences
107. Enhanced Switch…
• Example:
• Class z = new ….;
switch(z) {
case String.class:
:
break;
case Xxxx.class:
case Number.class:
:
break;
:
}
109. Get Compile Time
• Add Class method: long getCompileTime()
– Milliseconds since epoch
• Allows build time to be easily accessed
– Avoid class path walking, etc.
110. Basic JSON Support
• Example:
• String t =
“““{x**: 100, y: 1, z:”Hello!”}”””;
JsonObject jo =
JsonObject.parseJson(t);
System.out.printf(
“Value of x=%d”, jo[`x]);
jo[`a] = “World!”; // adds “a”
**: allow unquoted keys if only JavaId
JsonObject implements Map<String,?>; ? Restricted to null, String, Number,
JsonObject, List<JsonObject>
111. Basic XML Support
• Example:
• String t =
“““<xxx x=‘1’ y=‘2’ z = ‘3’>
<i>body text</i></xxx>”””;
XmlElement xxx =
XmlElement.parseXml(t);
System.out.printf(
“Value of xxx.y=%s”, xxx[`y]);
xxx << (new XmlElement(“zzz”) <<
new XmlTextNode(“…”));
XmlElement implements Map<String,String>; has List<XmlElement>
113. Pseudo Implements…
• Elsewhere
class LMN {
void doIt(
@implicitinterface ABC abc) {
abc.b();
}
}
• Any class that conformsTo(ABC) can be passed
as a valid argument (such as XYZ)
114. Partial Classes
• Example: in Xxxx.java
@partial public class Xxxx {
@property int x, y, z;
}
• Example: in Xxxx-partial1.java
@partial class Xxxx {
public int sum() {
return x + y + z;
}
}
All parts must be in same package (i.e., directory)
115. Partial Classes…
• Acts like: in Xxxx.java
public class Xxxx {
@property int x, y, z;
public int sum() {
return x + y + z;
}
}
116. Conditional Methods
• Example.
@conditional(
name=DEBUG, value=true)
public static void trace(
String format, Object… args)
{ .. }
• Usage
trace(“This call (and parameters)” +
“ may not be compiled: %s”,
“” + “ “ + … “”);
• Compiler Trigger: (say) -cond:DEBUG=false
117. Source Sections
• Add #section <name>/#endsection pre-processor
statements
• Used to mark source as a section
– Document purpose for range of source lines
– IDE can easily show/hide sections; direct navigation
– Nesting allowed
• Ex.
#section Public Classes
:
#endsection
118. Conditional Source
• Add #if <cond>/#else/#elif <cond>/#endif pre-processor
statements
– Tests debug symbols (missing symbol implies false)
– <cond> : boolean expression of id, ==,!=, >, >=, <, <=,
&&, ||, !, (,)
– Id set from command line; boolean/int/String only
• Compiler Trigger: (say) -D:DEBUG=false;LEVEL=11
• Ex:
#if DEBUG && LEVEL<10
:
#endif
119. Duplicate Methods in Interface
• Given:
interface X { void x(); void a(); }
interface Y { void y(); void a(); }
interface Z { void z(); void a(); }
• If used:
class A implements X, Y, Z { … }
• There are up to three a() methods to define
Some under the covers name mangling may be used, ex. X.a() a$X()
120. Duplicate Methods in Interface…
• Client Example:
class C {
A a = new …;
public void xxx() {
a.x();
a.a(); // call new a() def’n
a.X.a(); // call X.a() def’n
or
((X)a).a();
:
}
}
121. Parallel For
• Example:
AtomicLong sum = new …;
Map<String, ?> options = …;
parallelFor(var ti:
(0,1000)..<(0,2000); options) {
(int x, int y) = ti;
sum += x * y;
}
123. Actors Implementation
• Managers own 0+ Actors
• Managers manage
0+ Threads
• Actors buffer
0+ Messages
• Managers send
messages to Actors
• Actors use Threads to
process messages
*
* Thread
Manager Actor
*
Message
Per
Message
124. Services
• Example:
• In System Code:
– class MyService implements
MyInterface, Service {...}
:
Registry registry = System.getSystemRegistry();
MyService ms = new MyService();
Object id = registry.register(ms,
"MyInterface1",
new ServiceDescriptor(MyInterface.class, "1.5"));
registry.setValue(id, "test", "xxx");
125. Services…
• Example:
• In client Code:
– Registry registry = System.getSystemRegistry();
try (var sh = registry.
getRequiredService(MyInterface.class)) {
MyInterface mi = sh.resolveService();
:
// do something with mi
:
} catch(...) { ... }
Note: each use of this code could get a different implementation class
126. Service Dependency Injection
• Example (In some class):
• @inject(name=“datasource1”, deferredOk=false)
@property DataSource ds;
– Uses getRequiredService(DataSource.class,
“datasource1”)
• @inject(path=“xxx”, name=“anXxx”)
@property Xxx xxx;
– Uses getService(Registry.class, “xxx”).?
getService(Xxx.class, “anXxx”)
– If null; setup listener to set when defined
127. Utility Libraries
• Raise the bar (significantly) on the support
standalone JRE can provide
– Standardize behavior; extend closed classes
– Many sites want to constrain adding OSS
• Add utility methods/classes from popular Open
Source Projects
– Survey popular; ex. Apache, Google, SourceForge
– List TBD (and growing per Java release)
– Likely add many 100s of methods (fewer classes)
– Generally small (<100 LOC) and well tested in wild
Cost/Importance varies with scope/quantity of included libraries
128. Utility Libraries…
• Example of one such method: safe equality
• Add public static Object method:
boolean isEqual(Object l,
Object r) {
if(l == null)
return r == null;
else
return r == null ? false:
l.equals(r);
}
129. Utility Libraries…
• Example of one such method: consistent code
– Allows same syntax primitive or reference types
– No automatic conversion of primitive to wrapper
• But cast allowed: isEquals((Integer)1, (Number)2)
• Add public static Object methods:
boolean isEqual(
<prim>** l, <prim> r) {
return l == r;
}
** any primitive type
130. Property Definition
• Add @property field** annotation
• Causes automatic access method generation
– Unless programmer defined
• Supports simple, 1-dim array and generic
types
**: allowed in both class (bodies provide) and interface
131. Property Definition…
• Values:
– observable|vetoable=true|false
• Auto-generate add/removeListener
• Auto-generate fireListeners
– visibility: control access method visibility
• (public visibilities) rw(default), ro, wo; private
– name: alternate name (vs. field) to name the
property
**: allowed in both class (bodies provide) and interface
132. Property Definition…
• Example (in class X):
– @property(vetoable=true) String ssn;
• Generates code similar to this:
– private String _ssn;
– @const public String getSsn() {
return _ssn; }
133. Property Definition…
• Example (continued):
– protected void
_firePropertyChangeListeners(
PropertyChangeEvent e) {
// walk listeners with callback
}
– Listener may/may not throw VetoException
– More complex (ex. indexed) properties may have
more get/set methods
134. Property Definition…
• Example (continued):
– private List<PropertyChangelistener>
_listeners = …; **
– public void
addPropertyChangelistener(
PropertyChangelistener l) { … } **
– public void
removePropertyChangelistener(
PropertyChangelistener l) { … } **
**: only on topmost class needing this
135. Property Definition…
• Example (continued):
– public void setSsn(String ssn) {
try {
_firePropertyChangeListener(
new PropertyChangeEvent(
this, “ssn”, _ssn, ssn);
_ssn = ssn;
} catch (VetoException e) {};
}
– public X ssn(String ssn) {
setSsn(ssn);
return this;
}
136. Direct Property Access
• Implied use of get/set methods
• Example:
– class X {
@property int a, b, c;
public void xxx() {
a = b + c;
}
}
– In other class
X x = new x();
int z = x.a + x.b + x.c;
Becomes getC()
Only use get/set if field not visible (ex. private int a)
139. Extended Auto-Boxing
• On any use of a primitive expression if
followed by dereference operator (“.”, “.?”)
and a method call then auto-box the primitive
and apply the method to the wrapped value.
• Add utility methods to all wrapper types
– Ex: Integer.upTo(int max, Lambda)
1.upTo(10, x -> System.out.println(x)); **
– Java.lang.Math functions
– Etc.
**: Also can achieve as: 1..<10.each(x -> System.out.println(x));
140. Simplified Default Processing
• Example
int rc = Integer.parseInt(s)
default 0;
• If s is “55”; rc == 55
• If s = “bad value”; rc == 0
141. Delegate Fields
• Example:
– Given:
class X {
public static final int A = 1;
void a(); void b(); void c();
}
– Given:
class Y {
public static final int Z = 1;
void x(); void y(); void z();
}
142. Delegate Fields…
• Example:
– Given:
class Z {
@delegateto @property X x;
@delegateto @property Y y
void a() { … }
void b() { … }
void z() { … }
}
143. Delegate Fields…
• Example:
– Generates:
class Z implements X, Y {
public static final int A = 1;
public static final int B = 1;
private X _x;
private Y _y;
void a() { … }
void b() { … }
void c() { _x.c(); }
void x() { _y.x(); }
void y() { _y.y(); }
void z() { … }
}
144. Auto-generate common methods
• Example
@autoconstructors @autoequals
@autostring @autocompareto
class X implements Compareable
{
@forall @property
String name;
@forall @property
int age;
}
145. Auto-generate Constructors
• Allow addition of parameter:
– @auto value used as parameter value
• @auto(4) public Xxx(int a, int b, String s,
Thread t);
• Generates:
public Xxx(int a, int b, String s, Thread t) {
this(a, b, s, t, 4);
}
146. Auto-generate Constructor…
• Which allows:
• @auto(-1) public Xxx(int a);
• @auto(“”) public Xxx(int a, int b);
• @auto(null) public Xxx(int a, int b, String s);
• @auto(4) public Xxx(int a, int b, String s,
Thread t);
• @auto public Xxx(int a, int b, String s,
Thread t, int size); **
** parameter name must be same as field name
147. Struct Classes
• Many class are data-only (have little/no
behavior) so make them easier to create
• Add @struct class annotation
– @autotostring, @autoconstructors, @autoequals
@autocompareto** auto added
• All fields automatically have @property,
@fortostring, @forcompareto**, @forequals
**: if Comparable implemented
148. Struct Classes…
• Example
@struct class Data implements
Serializable, Comparable<Data> {
int[] array;
Date date;
String name;
}
149. Terse Methods
• Shorten single line non-void, concrete
methods
• Ex:
– public int calc(int x, int y) {
return x + y;
}
• Becomes:
– public int calc(int x, int y) =
x + y;
Note: very effective on getters – public int getCount() = count;
150. Terse Methods…
• Shorten multi-line non-void, concrete
methods
– Implied return value “result” of return type
– Single exit point (return statement not allowed)
• Ex:
– public int calc(int x, int y) = {
int z = calcZ();
result = x + y + z;
}
151. Static (utility) Classes
• Allow static modifier on top-level classes
– Makes all members implicitly static
– Changes default viability from “default” to public
– Makes any constructor, toString, equals/hashCode
declaration an error
– Auto create protected default constructor
– Can only extend by another static class
155. rationale
• Difference in operator support between
primitive types and reference types is highly
inconsistent and results in excessive source.
– Already recognized in special cases (ex. String +)
– Overloading adds to code brevity, readability
– Reasons for/against tend to be near religious
• Widely supported in other popular languages
• Most important for numeric, collection and
stream types.
156. Operator Overloading
• Allow custom definition of “operator”
methods in any class/interface
– Support many existing Java operators
– Add new Java operators
– Add casting capabilities (similar to numeric
primitives)
C+L
++++
$$$$
Cost depends on how much JRE supports this feature
157. Operator Overloading…
• “Operator” methods are just like other instance
methods but have unusual names
– Can override, overload, inherit; Select visibility
– In most cases a method already exists to implement
all/part of operator (ex. BigInteger’s add() for ‘+’)
– Create name mapping:
ex. + => $add (or $plus or _plus_ or ???)
– Compiler invokes method upon seeing operator
• Missing/inaccessible $<op> gets compiler error
– Unless built-in (ex. String +)
158. Operator Variants
• Given Class X, Y; instance x, y (Y may be X)
• Standard Operator Mappings:
– <op> x (ex. - x)
• Method: x.$<op>()
– <op> x, x <op> (ex. ++ x, x ++)
• Method: x.$x<op>(), x.$<op>x
– x <op> y (ex. x + y) (X & Y overload, use associativity)
• Method: x.$<op>(Y y)
– y <op> x (ex. y + x) (Y does not overload <op>)
• Method: x.$i<op>(Y y)
– x <op>= y (ex. x += y)
• Method: x.$a<op>(Y y)
• At least one of X, Y must be reference type
160. Operators…
Name (possible
method name)
Suggested
Method
Name
Precedence Note
&& Logical And 11 cannot
override
|| Logical Or 12 cannot
override
! Logical Not $lnot 1
161. Operators…
Name (possible
method name)
Suggested
Method
Name
Precedence Note
< Less Than $lt 5 Also Generic
Start
> Greater Than $gt 5 Also Generic
End
<= LT or Equal $le 5
>= GT or Equal $ge 5
== Equals $eq 6 Cond override
!= Not Equals $ne 6 Cond override
162. Operators…
Name (possible
method name)
Suggested
Method
Name
Precedence Note
<< Left Shift $lshift 4
>> Signed Right
$srshift 4
Shift
>>> Unsigned
Right Shift
$urshift 4
<<< Unsigned
Left Shift
$urshift 4 New
164. Operators…
Name (possible
method name)
Suggested
Method
Name
Precedence Note
<op>=
Augmented
Assignment
$a<op> 14
[]= Indexed
Assignment
$andx 0
[] Indexed
Access
$ndx 0
= Assignment 14 cannot
override
(…) Call $call 0 … not type
(…) Cast $cast 1 … is type
165. Operators…
Name (possible
method name)
Suggested
Method
Name
Precedence Note
** Power $pow 2 New
:: Bind $cat | $bind 13 New; maybe
:::
==> Send $send 13 New
<== Receive $rec 13 New
… Inclusive
$rng 10 New
Range
>.. Left
Noninclusive
Range
$xrng 10 New
..< Right
Noninclusive
Range
$rngx 10 New
166. Operators…
Name Precedence Note
? : Ternary 13 cannot override
?: Elvis |
Default
13 New; cannot override
?. Safe-
Reference
0 New; cannot override
. Member
Access
0 cannot override
new 1 cannot override
instanceof 5 cannot override
( … ) Sub-expression
0 cannot override; … not type
167. Operators…
Name
(possible
method
name)
Suggested
Method Name
Precedence Note
:x General
x is: + - / * %
& | ~ ! < >
$colon<op> Varies
based on x
New
x: General
x is: + - / * %
& | ~ ! < >
$<op>colon Varies
based on x
New
168. New Operators
• Given:Claxx X/Y, instance x/y
• Call operator ($call)
– ?? = x(…) x.$call(…)
• Cast operator ($cast)**
– ?? = (<type>)x x.$cast(<type>^^.class)
– Or: <type>.class.newInstance(x)
See new operators from other sections (ex. power(“**”) operator)
** iff not trivial conversion like up/down cast or numeric promotion or boxing
^^ reference and primitive (ex. Integer.TYPE)
169. New Operators..
• Index operator ($ndx)
– ?? = x[…] x.$ndx(…)
• Index assignment operator ($andx)
– x[…] = ?? x.$andx(??, …)
170. New Operators…
• Equals operator ($eq)
– x == y x.$eq(y) iff enabled; else sameAs(x, y)
• Also $ne, $lt, $ge, $gt, $le
– Pair (ex. $ne for $eq) auto-generated if missing
and other present.
– Ex. boolean $ne(? x) { return !this.$eq(x); }
• $eq() and equals() need to be consistent
– Say: boolean $eq(? x) { return this.equals(x); }
171. New Operators…
• New Binary operators:
– :x where x is: + - / * % & | ~ ! < > (maybe @)
• Left associative
– x: where x is: + - / * % & | ~ ! < > (maybe @)
• Right associative
• Intended to provide a reasonable set of new
operators to apply
172. Excluded Operators
• The following operators cannot be customized:
– Object Creation (new)
– Value Assignment (=) (but ?= and []= OK)
– Instance of (instanceof)
– Member reference (.)
– Ternary (x ? y : z)
– Short Circuit ( x && y, x || y)
– Field literal (.@)
– Safe Dereference (?.)
– Elvis (?:)
Last 3 are new operators (or separators)
177. Reference Initialization
• Allows easier initialization (less explicit use of
constructors, etc.) of reference types
• For any Class X, Y, to initialize an X from an
expression of type Y
– Use static method X X.valueOf(Y) or new X(Y)
– Must be unique choice or explicitly coded
• Allow trivial (ex. int -> long or boxing)
adjustment of Y first if needed
• Ex. BigInteger x = 10, y = “10”;
178. New Number Hierarchy
• Number
• Integral (abstract)
• Byte
• Char
• Short
• {Atomic}Integer
• {Atomic}Long
• BigInteger
• :
• Real/Fractional (abstract)
• Float
• Double
• BigDecimal
• Rational
• :
• Complex
Enables better placement of overloaded operator methods
179. Example Implementation
• Examples:
– In BigInteger
– public BigInteger $add(BigInteger other) {
return this.add(other);
}
– public BigInteger $add(String other) {
return this + new BigInteger(other);
}
– public BigInteger $iadd(Integral other) {
return new BigInteger(other.toString()) + this;
}
Only a partial set, many more for full implementation
180. Example Implementation…
• Example: In List - list intersection (sub-optimal)
• default public List<E> $and(
List<? extends E> xl) {
List<E> nl = Helper.makeNewList(this);
nl.addAll(this);
Iterator<E> it = nl.iterator();
while (it.hasNext()) {
E e = it.next();
if (!xl.contains(e)) {
it.remove();
}
}
return nl;
}
Only a partial set, many more for full implementation
181. Create a new Numeric Type
• @valuetype public class Fraction {
@property long num, den;
public Fraction(long num, long den=1) {
if(den == 0) throw new DivideByZeroException;
this.num = num; this.den = den;
normalize();
}
:
}
Only a partial implementation
182. Create a new Numeric Type…
• public Number $add(Fraction x) =
normalize(new Fraction(num * x.den +
x.num * den, den * x.den));
public Number $add(Long x) =
normalize(new Fraction(num + x * den, den));
public Number $iadd(Long x) =
normalize(new Fraction(x * den + num, den));
public Number $aadd(Long x) = **
$add(x);
:
**: auto-generated id omitted on @valuetype
183. Create a new Numeric Type…
• public double $cast(Double.TYPE) =
(double)f.num / (double)f.den;
public Double $cast(Double.class) =
(Double)$cast(Double.TYPE);
public double doubleValue() =
$cast(Double.TYPE);
:
public String toString() =
String.format(“%d:/%d”, num, den);
:
184. Create a new Numeric Type…
• Helpers
protected static Number normalize(Fraction f) {
long t = gcd(f.num, f.den);
f.num /= t; f.den /= t;
return f.den == 1 ? F.num : this;
}
protected void normalize() {
normalize(this);
}
protected int gcd(int x, int y) = …
:
185. Create a new Numeric Type…
• Add to Number classes
public Fraction $colonSlash(long x) =
new Fraction(this.longValue(), x);
public Fraction $icolonSlash(long x) =
new Fraction(x, this.longValue());
public Fraction $colonSlash(Number x) =
$colonSlash(this, x.longValue());
:
186. Value Types
• Java primitives are value (immutable and
identity-less) types where ++x; x++; --x; x--; x
+= 10 and similar create new values
• On reference types these operator instead
update the receiver (via a method)
• Many Java reference types behave as values
types (ex, String, Number) and should be
treated as such: i.e., x++, x += y create new
C+L
+
$$
187. Value Types…
• Add the new @valuetype class annotation.
– copy constructors generated if missing; default
constructor, setters not allowed
– Compiler can auto-gen any missing ?=, --/++
methods
• Apply to JRE types as appropriate (ex.
Numbers)
189. rationale
• It should be easier to import names into a
compile unit
– Finer selection
– Finer location (vs. whole unit)
– Produce more conventional names
• It should be easier to migrate to new field /
method names over time
190. Import Aliases
• Allow imported type, field and method names
to have aliases
– To update to new conventions; library adoption;
personal preference
• Import {static} <baseName> as <alias>, …
– Only alias defined
• Import {static} <baseName> add <alias>, …
– BaseName and alias defined
C
+++
“add” can be ‘+’; “as” can be ‘=‘
$$
191. Terser Imports
• Reduce redundant text when importing
multiple types from a single package
• import <baseType> {:<simpleType}…
• Extend wildcards: can occur 0+ times anywhere in
name
– * == 0+ characters; ? == exactly 1 character
C
++
$$
192. Package Imports
• Create partial package imports
– Help eliminate base name crashes from multiple
packages
– Brevity
• import <package> as <alias>
C
+
$
193. Multiple Imports/Import Blocks
• Allows import to be scoped
– Import can occur in any class/interface/enum
• At start of body
• Symbols defined only in that type and nested children
– Import can occur in any method and/or block
• At start of method/block
• Symbols defined only in that method/block and nested
children
– Import can have optional block
• Can be anywhere in method/block
• Symbols defined only in child block
• Can nest indefinitely
C
++
$$
194. Type Aliases
• Allow complex types to be shortened
– Some overlap with import
• Alias is same as base type
• typealias <baseType> as <newType>, …
– <newType> now acts like reserved word; ie. no
variable can have that name in same scope
• Use anywhere a declaration is allowed
C+BC
Can be class & method member (preferred) or just compiler (after imports)
++
$$
195. Method Aliases
• Allow methods to have alias names
• methodalias <methodSig> as <nameName>, …
• methodSig is like static reference without
values:
– Ex. String.substring(int, int)
– Empty parameters: (void)
– All overloads: (…)
• Use anywhere a method declaration is
allowed
C+BC
++
Can be class & method member (preferred) or just compiler (after imports)
$$
196. Field “Alias” by Annotation
• Leverage JavaBeans
• Auto-generation of access methods
• @alias(“x, y, z”) private int xxx
– Perhaps @alias(“x, y, z, xxx”) private int _xxx
C
+
$
197. Field “Alias” by Annotation…
• Examples:
– Generates:
– private int _xxx
– and public …
• int getX() { return xxx;}; void setX(int $v) { _xxx = $v; }
• int getY() { return xxx;}; void setY(int $v) { _xxx = $v; }
• int getZ() { return xxx;}; void setZ(int $v) { _xxx = $v; }
• Possibly also (for x, y and z):
<thisClass> x(int $v) { _xxx = $v; return this; }
198. Method “Alias” by Annotation
• Auto-generation of methods
• Visibility same as base method
• @alias(“pqr, lmn”) public int xyz() { … }
• @Deprecated only effects base method
C
+
$
199. Method “Alias” by Annotation…
• Examples:
– Generates:
• public int pqr() { return xyz(); }
• public int lmn() { return xyz(); }
201. rationale
• Java needs easier to use immutable types (to
enable easier parallelism, for one).
• Java should provide comparable types offered
by many popular languages
• For ease of use, such standard types should
support literal notation.
202. Map/List Literals
• Java has array literals, it needs to add literals
for common collections
• List literal: [ <value>,… ]
• Map Literal : { <key>:<value>, … }
• Type is least common sub-type of key/value
• Literals can be passed to constructors to set
type (or cast to type)
– new ArrayList([1,2,3]) or (ArrayList)[1,2,3]
May need to use #[…] and #{…} format
C+L
++++
$$
203. rationale
• Most languages that support collections like
lists, tuples, maps, etc. have some literal from
for each type. Java does not.
• To match ease-of-use add the missing literal
syntax
204. Implementation
• literals create new instances upon each reference
(they act as templates).
• The following creates 100 lists (thus the client
can freely modify each copy).
for(int i = 0; i < 100; i++) {
List<Integer> l = [ 1, 2, 3 ];
l << new
Random().nextInt(100);
}
• Use Arraylist and LinkedHashMap as default
implementations
205. As
• Make instanceof operator safer
– Reduce boilerplate if tests
• Add public static Object methods
– <T> T as(Class<T> type, Object** o )
– <T> void as(Class<T> type, Object o, <lambda>)
• Cannot throw NullPointerException
– Returns null instead
C+L
+++
** overloaded (independently) on primitives and Object
$
206. As…
• Example:
if(o instanceof Integer) {
Integer n = (Integer)o;
System.out.printf(
“%d%n”, n + 1);
}
• Vs.
as(Integer.class, o,
Integer n -> System.out.printf(
“%d%n”, n + 1) );
207. As…
• As implements standard casting unless object
implements the new Castable interface which
provides the cast mechanism
– Method: <T> T castTo(Class<T> type)
– If cannot make cast, throw ClassCastException
• Ex. class X implements Castable { … }
• X x = new …;
• Y y = (Y)x; x.castTo(Y.class)
208. Collection Initialization
• Arrays support initialization
new Object[] { <value>,… }
• Collections should also:
C+L
+++
– Add new interface Loadable<T**> with methods
• void load(T)
• void load(T[])
• void load(Collection<T>)
– Wrap values in { … } immediately after constructor
call
** T same as collection member type
$
209. Collection Initialization…
• Examples:
• List<> l = new LinkedList<Integer>() { 1, 2, 3 }
• Map<> sm = new HashMap<Integer,String>()
{ 1:”1”, 2:”2”, 3:”3” }
• Key:Value pairs wrapped in Entry<K,V> class
• All JRE collection classes implement Loadable
– Load method differs from insert/add/append/put
in that it works only if no other method called
before it (else IllegalStateException)
210. Tuple Type
• Utility of array; flexibility of List
– Implicit conversion to/from array
• Immutable fixed-size list
– Can be of mixed type; supports generic types
– Comparable: by length, then members
• Literal Syntax: ( <value>, … )
• Factory methods (Tuples.make) available
• Allows multiple Assignment:
(int x, double y, var s) = (1, 2.0, “Three”)
• Makes it easy to return multiple values
C+L
+++
$$
211. List Type
• Functional Style List
• Implicit conversion to/from java.util.List
• Immutable composition
– head::tail or Lists.Nil
– Apparent changes create new, like with String
– java.util.List like behavior + flatten()
• Literal Syntax: item1::(item2::(item3::Lists.Nil)))
• Factory methods (Lists.make) also available
• New “::” (maybe “:::”) ($cat) operator
C+L
++
$$
212. Range Type
• Allow a concise representation of an
immutable sequence of values
– Often numeric but can wrap collections
• Literal Syntax: <start> …|..<|>.. <end>
{ … <step>}
• Factory methods (Ranges.make) available
– Can use any Rangeable ** type (+ all primatives)
• New “…”, “>..”, “..<“ ($rng, $xrng, $rngx)
**: Like Iterable (may be same)
C+L
++
$$
213. Matrix Type
• Allow a dense representation of a multi-dimensional
regular (vs. ragged/sparse) arrays
– Cells often primitive but can any type
– Allocation is packed in memory (bit: 8 per byte)
• Access Literal Syntax: <variable>[ <index>, …]
– allows [x,y,z] (instead of [x][y][z])
– Support 10+ dimensions (product >0 && <=MAX_INT)
• Supply standard matrix algebra operations
• Factory methods (Matricies.make) available
– Create matrix and (sub)view on another matrix
C+L
++
$
Simplified Subset of JSR 83
214. Matrix Concept
• 3-dimensional [N, M, L] Matrix
– N * M * L cells
• View on Matrix
• View on View
• Can also view as
vector
(1 dimension
N * M * L long)
• Can update through
view
Ignore labels
From http://www.altera.com/technology/system-design/articles/2013/scanned-radar-signal-processing.html
215. Matrix Access…
• Whole Matrix and View (AKA sub-range)
• Picture shows
possible
additional options
(stride, selection,
partition, etc.)
• Do provide transforms
like flip and transpose
http://incanter.org/docs/parallelcolt/api/cern/colt/matrix/doc-files/slice.gif
216. Potential Functionality
• Get and set the cell @ index
• Get rank and shape
• Apply Math.* operations to all elements using lambdas
• Operations to transpose, inverse, etc.
• For liked shaped:
– Standard operations (ex. +, -, *, /)
– CompareTo elements (produce array of ints)
• Reduction functions (sum, min/max value, etc.) using
lambdas
• (Consider) array construction functions (merge, pack,
spread, unpack)
• Parallel operation variants where no cross-cell contention
217. Matrix Type
• Examples:
– IntMatrix m = Matrices.make(
Integer.TYPE, int[]{10, 10, 10});
– Matrix vm = Matrices.makeView(m,
int[] {1}, int[]{2, 3}, int[]{5, 5});
Assume “==“ overloaded to equals(); “[]“ overloaded
218. Matrix Type
• Examples:
– int x = m[1,1,1];
– m[9,9,9] = x;
– Same effect:
– var dims = m.getDimensions()
– m[9 * dims[0] * dims[1] + 9 * dims[1] + 9] = x;
Assume “==“ overloaded to equals(); “[]“ overloaded
220. rationale
• Enhanced accuracy and safety in calculations
• Extended domain of application (science,
engineering, etc.)
• Make more consistent
– Add java.lang.Math functions for all (not just
primitive) numeric types
221. Rational Type
• Allow accurate representation of fractional
values (such as decimal 1/3 or binary 1/10)
– New Number subclasses
– Support matching int/long/BigInteger as
numerator/denominator; allow normalization
C+L
+
$$
• Literal syntax: x :/ y (x, y some integer, y != 0)
• Factory (Rationals.make)
• Add similar Java/JRE support as Double has
222. Complex Type
• Allow representation of complex values
– New Number subclasses
– Support matching double/BigDecimal as real/imag
• Literal syntax: x +|- yI or x @ y (x, y some
non-complex number)
– ‘I’ can be I, i, J, j (compile-time only, no idouble)
• Factory (Complexes.cart, Complexes.polar)
• Add similar Java/JRE support as Double has
C+L
+++
$$
223. Unit & UnitValue Types
• Avoid logical errors on arithmetic across
different units (ex. adding Apples & Oranges)
– New Number subclasses
– Add a unit to any number
– Exceptions if inconsistent units in arithmetic
– Can combine units and numbers with units
• Factory (Units.make, UnitValues.make)
• Add similar Java/JRE support as Number has
C+L
+
$$$
Much simpler approach than JSR 275; perhaps cleaner than JSR 363
224. Unit Type
• Unit
– Defines a unit that can be applied to a value
– Only compatible units in an operation
• Ex. + requires same units, * can combine units
– Units can be combined
225. Unit Type…
• UnitValue
– A Number that also has a Unit
• Can be used anywhere a Number is allowed
– Overloaded operators supported
• Parallel to Number type hierarchy
– IntegerUnitValue extends Integer, etc.
– Make Integer, Double, etc. nonpackagefinal to accomplish
• Alternate**: update existing Number classes to add
Unit
– Numbers with null unit acts as Numbers do today
**: Number instances are larger; subtle backwards incompatibility
226. Unit Type…
• Subtypes:
– PrimativeUnit – ex: gram, second, meter, degreeKelvin
– Derived/ScaledUnit – ex. kilogram, millisecond,
kilometer, degreeCelcius
• Can register scale converters (similar to int float)
– CompoundUnit; ex. newton, hertz, speed
• Can register formatters per unit (similar to
SimpleDateFormat)
• Unit registry (localized) to access units
• Add many(perhaps 100s) “standard” units
– No implied naming standard; users gives name
227. Unit Type…
• Examples:
– Unit gram = Units.makeUnit("Gram", "g", "gram",
java.units.Gram);
• Can have equivalents with different locales
– Number UnitValues.make(<numeric primitive>,
Unit unit);
– Number UnitValues.make(<Number**> value,
Unit unit);
**: not UnitValues
228. Checked Arithmetic
• Allow for overflow/underflow detection
• Add @checked(overflow=true|false|promote,
underflow=true|false|promote) method annotation
– Generally used on methods containing only computations
– Throws new Overflow/UnderflowException extends
RuntimeException
– Applies to arithmetic and casts
• Add static <type> xxxChecked(<type> other) family of
methods on primitive numbers where xxx is an
operator (ex. add, multiply); generally native methods
• Promote value causes type expansion (ex. Long
BigInteger) to avoid condition if Number type used
C+L
++
$$
229. Checked Arithmetic…
• Examples: Some generate exceptions
assume all in @checked(promote=true) method
– Number x = 1; x << 50 - Integer BigInteger
– Number x = 1024 >> 10 - Integer Double
– Number x = 0x7FFFFFFF + 1 – Integer Long
– Number x = (int)1FFFFFFFFL – overflow (sig bits lost)
– Short s = (short)(65 * 1024) – ditto
• Casts can prevent promotion
230. Checked Arithmetic…
• $<op> methods can accept an optional
additional int parameter
– Bit flags for overflow, underflow, promote
– Example.
• Given: Integer x, y, z;
• In @checked(overflow): z = x + y;
• Becomes: z = x.$add(y, Checked.overflow);
231. Power Operator
• Allow xy to be expressed as an operator (vs.
function) x ** y
– New right-associative binary “**” (AKA
$power/$starstar ) operator
• Add similar Java/JRE support as * (multiply)
has; on all numeric types (primitive and Big)
• Example:
– long x = 2**45; double y = Math.PI**-3.5**2
Assume “**” overloaded; Suggest creating BigMath class like Math class
C+L
+
$
233. rationale
• Java needs increased ease-of-use and self-consistency
• Java should provide comparable utility
features offered by many popular languages
234. “Class” literal Extensions
• Existing Class Literal: <className>.class
• New Package Literal:
<packageName>.package
• New Field Literal:
{<className>.}@<fieldName>
• New Method Literal:
{<className>.}<methodName>(<type>
{,<type>}…|void)
• All resolved (tested to exist) by compiler
{<className>}: optional when inside that class; class name can be qualified
C
$
+
+++
235. Method Bindings
• Bind a method and its receiver
– First class combo (not a closure)
– Overloads operator “::” (maybe “:::”) to create
• Allows “currying” via get/setParameter
– Also via overloaded operator “…”
– aBinding…1…2 sets the first 2 parameters
• Allows rebinding via get/setTarget
• Overloads $call
C+L
+++
$$
236. Method Bindings…
• Example: (cont)
• Effectively invokes:
– String s2 = s.substring(0, 10);
• But actually invokes:
– String s2 = substring.$call(0, 10);
• Which then calls
– method s.substring(0, 10)
• via reflection or other means.
** an interface with at least one implementation
237. Method Bindings…
• Binding supports a Boolean property: async
– If true $call() may run on a separate thread
• Implementation should use Executors
• So may support additional configuration properties
– $call will return a Future<T> (T is original return
type) to allow monitoring of the progress
– Intended to be used on only heavy-weight (does
I/O, etc.) methods
238. Method Bindings…
• Example:
– MyIOService s = …;
var f = (Future<Integer>)
MyIOService.copyTree(File, File)::s
.setAsync(true)
.$call (new File(“.”),
new File(“elsewhere”));
: do other stuff
int rc = f.get();
Optional text
239. Add “Chaining” Setter
• For field “<type> xxx” JavaBeans defines
access methods as:
– <type> get/isXxx() { return xxx; }
– void setXxx(<type> v) { xxx = v; }
• Add new setter:
– <thisType> xxx(<type> v) { xxx = v; return this; }
• This allows “fluent” assignments like:
– Xxx xxx = new Xxx().aaa(1).bbb(3).ccc(3);
• Retrofit into all JRE classes
L
+++
$$$$
240. rationale
• Long sequences of setter can get tedious
• Example:
• Xxx xxx = new Xxx();
xxx.setAaa(1);
xxx.setBbb(3);
xxx.setCcc(3);
• These need to be made less repetitive
• This is a common pattern JRE should fully embrace
241. Versioned Types
• Applies to Class, Interface, Enum
• Each type can have version suffix:
[<major>{,<minor>{,<fix>{,<comment>}}}]
• Matching on (internal) class name (#s only)
– for class Xxx[1.2.3.zzz] name is Xxx$$v1v2v3vzzz
• Annotation better but requires full class path scans
– first matching on class path wins
• System class loader change
C+L+VM
– Compiler can generate multiple versions of source;
highest version also generated wo suffix
+
$$
242. rationale
• Often need to evolve classes incompatibly
– Change method name/param/return type
– Resort to new class name (ex. Xxxx2) or package name
(xxx.yyy.v2)
– This is difficult to manage
• Alternate needed that allows most classes to be
referenced by name alone
– Typically unadorned; occasionally with specific
version/version range
– Ex. Xxx (any version) vs. Xxx[2.0,] (any 2.0+)
243. New Final Variant
• Final on methods prevents overriding.
– Often to restrictive
– Often it is safe to allow classes in the same
package to override (i.e., same careful authors)
• Add new “nonpackagefinal”** keyword
– Method can be overridden only by classes in same
package
• Expected to be useful for java and javax
packages (ex. Number subclasses)
**: looking for better name
C+L+VM
+
$
244. Pseudo Methods
• Add dynamic methods to a class
• New interface: SupportsPseudoMethods**
– Method: Object onMethodCall(String
methodName, Object... args)
– Implements “missing” (maybe all) methods
• Compiler redirects to above whenever a
(statically, not via reflection) method is
invoked that does not exist
C+L
++++
$
**: looking for better name
245. rationale
• Many languages allow classes to dynamically
add method behavior.
– This allows for very flexible capabilities, such as
meta-programming
– Wo/complex means (such as AOP)
• Java needs a similar capability
246. Pseudo Methods…
• Assume class Expando implements
SupportsPseudoMethods
• Assume Expando class has methods:
– normalMethod1(), normalMethod2() and
onMethodCall()
• onMethodCall has cases for:
– nowDate(), nowMillis() and other()
247. Dynamic Variables
C+L
+++
$
• Add a new field and local variable annotation
@dynamic (allowed only on Object or Object[]
types)
– tells the compiler to ignore type safety on any
method call
– Causes dynamic (via reflection, invokedynamic,
etc.) calls
– Suggest add method to Object to facilitate making
these dynamic calls: $dynamicCall and
$canDynamicCall
248. rationale
• May languages support similar behavior, often
call duck typing
• At the loss of some compile time proven
correctness, such variables are very flexible
• Java needs similar flexibility
249. Var Type
• Use initial value to imply variable type
– Explicit type only needed if type different from
initial value’s type (say a superclass)
– Saves significant typing; allows easier type change
• @property var count = 1; 1L;
• Define new type “var” that accepts the value’s
type
– Declarations: var x = <expr>;
– For: for(var x: <iterable>) { … }
C+L
++
$
250. Var Type…
• Example:
– Integer ten = new Integer(10);
– int thirty = 30;
– int twenty = 20;
– long ninety = 90L;
– String name = "Barry";
– double y = 30.5;
– LinkedList<String> stringList1 = new
LinkedList<String>();
– Number x = new Integer(20);
– List<String> stringList2 = new LinkedList<String>();
251. String Enhancements
$
• Simple (JavaIdCharacter content only):
`this_is_a_string (makes great hash key)
• Long Strings:
“”” any text here, including “ and ‘ and n and
line ends until the next “””
• Raw Strings (ignore ‘’ as escape):
– “this is not an escape”R (or r)
– Also “”” … “””r
C+L
+
+++
++
252. String Enhancements…
• Smart Strings:
~“””${name} is
${age > 50 ? ”old” : “young” }””” **
– Simple id reference can be shortened: $name
• Causes any ${<expr>} to be replaced by the value
of the <expr> evaluated in current context
– May cause internal Map to be sent to interpolate()
with all (perhaps just referenced in expr) variables in
current context.
**: overloaded operator does “interpolate()” (ah la Perl/Groovy) behavior
+
253. String Enhancements…
• Unified StringBuilder/Buffer and String
+++
– Create new Interface Stringy that covers all String
instance methods
– Make StringBuilder/Buffer implement Stringy
• So they can be used most places Strings are
• Replace most JRE methods String parameters with
Stringy type
– The compiler will treat Stringy items as String (ex.
x + y)
254. Size Enhancements
• Unify size determination
– Add new Interface Sizable with method: int size()
– Add method and/or interface to all JRE classes
with size(), length() or getLength() methods
• Ex. Add CharSequence method: default int size() =
length()
• Consider adding int size() to array classes
+++
255. Default Positional Parameters
• Allow optional default values for parameters
– Added convenience; many languages support them
• Parameter Syntax:
<modifier>… <type> <name> { = <value>}
– Defaulted parameters must come after all non-defaulted
parameters; omission applied right-to-left
– Values must be constant expressions or null
• Works by generating methods with/without
params and calling all param version
– Unless provided by programmer
C+L
++
$
256. Reference Parameters
• Add new @ref ** parameter annotation
– Allows pass-by-reference parameters
– Allows multiple return values
• Actual parameter values must be a variable
(vs. expression) so it can be assigned to
• Variables passed must also be declared @ref
• Implementation may implicitly auto-box
variable and pass boxed value by value
**: perhaps @inout
C+L
+
$
257. “Keyword” Parameters
• If last constructor or method parameter is
Map<String,?> (like … works) you can use a
map literal as last parameter
C+L
++
$$
– Normal form: {k1:v1, k2:v2}
– Concise form: k1:v1, k2:v2
– Actually can intermix with positional parameters
258. “Keyword” Parameters…
• If no map as last parameter on a constructor
use this sequence for keyed values:
– Xxx xxx = new Xxx(1, 5);
– xxx.setX(1);
– xxx.setY(2);
– xxx.setZ(3);
• “Defaults” for keys:
– Add new Map method: Map putIfNew(key, value)
– Use in called method to set “defaults”
259. Pseudo Instance Methods
• Redirect undefined (unless SupportsPseudo-
Methods processing) methods to best known
(imported) matching static methods
– Match if name same, first param is receiver type (or
supertype), other params match in turn
– Match must be unique or compiler error
• Only on instance methods
• At compile-time only
• Even on final classes
• Not polymorphic, but overrideable
C+L
+++
$
260. Pseudo Instance Methods…
• Examples:
• Given:
– public class X { … }
– public class SomeUtilClass {
public static void doThis(X x, int a, in b, int c)
{…}
public static void doThat(X x, int a, in b, int c)
{…}
}
261. Pseudo Instance Methods…
• Examples:
– Class X has no doThis/doThat methods
• These calls:
• X x = new …
• x.doThis(1, 2, 3)
• x.doThat(3, 2, 1)
• Becomes:
• SomeUtilClass.doThis(x, 1, 2, 3)
• SomeUtilClass.doThat(x, 3, 2, 1)
262. Constant References
• Final on primitives implies constant
• Final on references allows referent to still change
• Add new reference variable annotation @const
which disallows update of referent
– No assignment to referent fields
– No use of non-const methods via reference
• Allow @const on instance methods, which
indicates method does not mutate** receiver
• Apply to JRE methods as appropriate
– @property adds @const on getters
C+L
++
**: can allow internal only changes (ex. normalize a rational value)
$$
263. Stable (pure) Methods
• Some methods, given the same inputs, will
always produce the same outputs. If the
compiler (source/JIT) knows this, optimizations
are possible.
• Add a method @stable annotation which allows
the optimization of repeated (in source or loop)
method calls to be cached
– Only if the compiler can detect that the parameters
are the same on each call
• Annotate all @stable JRE methods
– Ex. Math.min()/max()
C+L
+
$$
264. Stable (pure) Methods…
• Stable parameters:
– Compiler flows indicates not changed
– Type is:
• Immutable (including primitives and null) or Value Type
• Accessed via @const Reference
• Result of another stable method
• Add new @immutable annotation
– Marks type as immutable (often also with @valuetype)
• Type should** have no mutators
– Mark all immutable JRE types (ex. Numbers)
– Add annotation to Collections immutable method returns
**: can allow internal only changes (ex. normalize a rational value)
265. Specialized toString
• Split toString() into
– humanToString() – intended for humans
• May be minimalist (like String.toString())
– debugToString() – intended for programmers
– Should always look like Object’s toString
– Each type selects which form toString() uses
L
++
$$$
Cost depends on how much JRE adopts this approach
266. Specialized toString…
• Make each xxxxToString() method composable
– xxxxPrefix(), xxxxBody(), xxxxSuffix(),
xxxxBodyStart(), xxxxBodyEnd()
– All take StringBuilder arg
– Perhaps all start with ‘$’
267. Specialized toString…
• Ex:
public String debugToString() {
StringBuilder sb = new ..;
$debugPrefix(sb);
$debugBodyStart(sb);
$debugBody(sb);
$debugBodyEnd(sb);
$debugSuffix(sb)
return sb.toString();
}
• Allows subclasses opportunity to override minimally (ex. override
$debugBody() only)
– @autotostring supports this structure
268. Get Compile Time
• Add Class method: long getCompileTime()
– Milliseconds since epoch
• Allows build time to be easily accessed
– Avoid class path walking, etc.
L
+
$
269. For with Index
• Enhance the “Enhanced For” Statement to
provide index and count
– Provides index of current iteration
– Provides max number of iterations
• Syntax ex:
for(int i, len; String s: aStringArray) { … }
– Optional first int has current index (0+)
– Optional second int has length (if known)
– “int” type fixed so optional
C
+
$
270. Enhanced Switch
• Add new interface Case with method
boolean matches(Object other)
• Switch can test any type implementing Case
– Use if/else If/else implementation
– Implement Case on (at least) any JRE Comparable
class and enums
– Consider adding Object method matches() so all types
can be used in switch (thus no Case interface needed);
defaults to calling equals()
• Can eliminate special String/enum support
• More readable than if/else if/else sequences
C+L
+++
$
271. Enhanced Switch
• Example:
• Class z = new ….;
switch(z) {
case String.class:
:
break;
case Xxxx.class:
case Number.class:
:
break;
:
}
272. Enhanced Switch…
• Allow “goto” case instead of break
• Class z = new ….;
switch(z) {
case String.class:
:
break;
case Xxxx.class:
case Number.class:
:
goto String.class;
}
+
273. Enhanced Switch...
• An alternate to:
– Allows finer control over flow (vs: top down only)
– Some sequences cannot be done in strict top-down
• Class z = new ….;
switch(z) {
case Xxxx.class:
case Number.class:
:
case String.class:
:
break;
:
}
274. Appendable Ehnancements
• Make Appendable more like Streams
– default Appendable
appendln(CharSequence cs) {
append(cs); append(‘n’);
return this;
}
– default Appendable
appendf(String fmt, Object…va) {
append(String.format(fmt, va);
return this;
}
L
++
$
275. Basic JSON Support
• Add basic++ JSON support based on
collections
– New JsonObject extends TreeMap<String, ?>
– New JsonArray extends ArrayList<?>
– Values restricted to: null, String, Number**,
Boolean
– Both have static parseJson(String) to parse
– Has String toJsonString(boolean formatted)
– Both implement new JsonValue marker interface
++ way less than Java API for JSON Binding; **: perhaps just Double
L
++
$$
276. Basic XML Support
• Add basic XML support based on collections
– New XmlNode interface/ XmlTextNode impl
• Method: String getText()
• Method: String toXmlString(boolean formatted)
– New XmlElement extends LinkedHashMap<String,
String> implements XmlNode
• Map holds attributes
• Contains: @property List<XmlNode> elements
• Has static parseXml(String) to parse
• Has static to/FromDom for DOM integration
No support to see other XML (instructions, comments, etc.)
L
+
$$
277. Simplified Serialization
• Serializing into a stream is often awkward
– Large amount of overhead
• Serialize into List or Map (vs. Stream)
– Much easier to manipulate
– Can stream serialize resulting map/list if needed
– Target/members must still be serializable
– Reference loops allowed
– May lose primitive vs. wrapper type distinction
– May lose array vs. collection distinction
• Add utility methods to serialize/deserialize
L
+
$$