144 points · by agluszak · 3y ago · 256 comments
// Java 21
if (obj instanceof Point(int x, int y)) {
System.out.println(x+y);
}
// Older Java
if (obj instanceof Point p) {
int x = p.x();
int y = p.y();
System.out.println(x+y);
} if (obj instanceof Point) {
Point p = (Point) obj;
int x = p.x();
int y = p.y();
System.out.println(x + y);
}I hope someone will design some jvm SimpleLang eventually, which will have very few syntactic constructions but cover all/most of use cases.
As for there now being multiple ways to write the same thing, this seems like something that could be easily linted into consistency. So you would really only have to learn the less verbose way for any newer Java projects.
yes, new SimpleLang can have lessons learned during last 20 years implemented, as in example from another commenter: https://news.ycombinator.com/item?id=37068380
Currently, for a given task, Java usually have 5 legacy deprecated ways to solve, and two more in newish Java versions, and dev needs to keep all of them in memory to be able to read and understand other's code.
> As for there now being multiple ways to write the same thing, this seems like something that could be easily linted into consistency.
that's if you don't work with any legacy systems and 3p libraries and never switch projects/jobs
IMO it's a significant syntactical improvement, as it considerably reduces boilerplate assignments.
the problem is that Java not modern language, but carrying all legacy features from last 20 years, so having all legacy features + new modern creative ideas make Java very complex.
I mean, how are you going to use it? Something like this?
Point p = getPoint();
if (p instanceof Point(int x, int y)) {
System.out.println(x+y);
}
... that seems pretty bad. Or am I missing something?(let [p obj]
(if (instance? Point p)
(let [x (.x p)
y (.y p)]
(println (+ x y)))) (if (? p::Point obj)
(... p:x p:y))
This succeeds if obj matches the pattern p::Point, declaring p to be the value of obj coerced to a Point.
This is integrated with Kawa's static type-checking/inference.but if it is a java record class, then there's currently no standard library way, since it's not a bean (getter/setter naming of properties). You'd have to write custom code for it, which sucks.
Using quasiquote-style pattern:
(if-match ^#S(point x ,x y ,y) obj
(prinl (+ x y))
Or using @(struct ...) pattern operator: (if-match @(struct point x @x y @y) obj
(prinl (+ x y))
All done with macros. Expansion, compilation, disassembly: 4> (flow '(if-match @(struct point x @x y @y) (new (point 1 2))
(prinl (+ x y)))
expand
prinl
compile-toplevel
disassemble)
(let ((#:g0062 (struct-from-args 'point 1 2)))
(let* (#:result-0065
x y)
(if (if (subtypep (typeof #:g0062)
'point)
(let ((#:x0063 (slot #:g0062 'x))
(#:y0064 (slot #:g0062 'y)))
(sys:setq x #:x0063)
(sys:setq y #:y0064)
(sys:setq #:result-0065
(prinl (+ x y)))
t))
#:result-0065
())))
data:
0: point
1: 1
2: 2
3: x
4: y
syms:
0: struct-from-args
1: subtypep
2: typeof
3: slot
4: prinl
5: sys:b+
code:
0: 2003000E gcall t14 0 d0 d1 d2
1: 04000000
2: 04020401
3: 20010005 gcall t5 2 t14
4: 000E0002
5: 20020002 gcall t2 1 t5 d0
6: 00050001
7: 00000400
8: 38000016 if t2 22
9: 00000002
10: 2002000A gcall t10 3 t14 d3
11: 000E0003
12: 00000403
13: 20020009 gcall t9 3 t14 d4
14: 000E0003
15: 00000404
16: 20020006 gcall t6 5 t10 t9
17: 000A0005
18: 00000009
19: 2001000D gcall t13 4 t6
20: 00060004
21: 1000000D end t13
22: 10000000 end nil
instruction count:
10
#<sys:vm-desc: 9966330>
I see this is doing something silly: (subtypep (typeof x) y) is just (typep x y), but costs an extra gcall instruction.Either the pattern matcher should do this, or the compiler should have that as an algebraic reduction, or both.
Let's do the compiler for fun:
$ git diff stdlib
diff --git a/stdlib/compiler.tl b/stdlib/compiler.tl
index 58685741..a837571e 100644
--- a/stdlib/compiler.tl
+++ b/stdlib/compiler.tl
@@ -1411,6 +1411,8 @@ (defmeth compiler comp-fun-form (me oreg env form)
(set form (rlcp ^(,bin ,a ,b) form)))
((- @a)
(set form (rlcp ^(neg ,a) form)))
+ ((subtypep (typeof @a) @b)
+ (set form (rlcp ^(typep ,a ,b) form)))
((@(or ignore nilf) . @args)
(if (eql sym 'ignore)
(each ((a args))
Note that we are using pattern matching here to recognize and rewrite this case. In return we will obtain better code from pattern matching: $ make
TXR stdlib/compiler.tl -> stdlib/compiler.tlo
$ ./txr
This is the TXR Lisp interactive listener of TXR 291.
Quit with :quit or Ctrl-D on an empty line. Ctrl-X ? for cheatsheet.
TXR is not a toy, but should be kept within easy reach of children.
1> (flow '(if-match @(struct point x @x y @y) (new (point 1 2))
(prinl (+ x y)))
expand
prinl
compile-toplevel
disassemble)
(let ((#:g0024 (struct-from-args 'point 1 2)))
(let* (#:result-0028
x y)
(if (if (subtypep (typeof #:g0024) ;; this hasn't changed, of course
'point)
(let ((#:x0026 (slot #:g0024 'x))
(#:y0027 (slot #:g0024 'y)))
(sys:setq x #:x0026)
(sys:setq y #:y0027)
(sys:setq #:result-0028
(prinl (+ x y)))
t))
#:result-0028
())))
** expr-1:1: warning: if-match: no such struct type: point
** expr-1:1: warning: new: point does not name a struct type
data:
0: point
1: 1
2: 2
3: x
4: y
syms:
0: struct-from-args
1: typep ;;; no mention of subtypep here any more!
2: slot
3: prinl
4: sys:b+
code:
0: 2003000E gcall t14 0 d0 d1 d2
1: 04000000
2: 04020401
3: 20020002 gcall t2 1 t14 d0
4: 000E0001
5: 00000400
6: 38000014 if t2 20
7: 00000002
8: 2002000A gcall t10 2 t14 d3
9: 000E0002
10: 00000403
11: 20020009 gcall t9 2 t14 d4
12: 000E0002
13: 00000404
14: 20020006 gcall t6 4 t10 t9
15: 000A0004
16: 00000009
17: 2001000D gcall t13 3 t6
18: 00060003
19: 1000000D end t13
20: 10000000 end nil
instruction count:
9 ;; down by one
#<sys:vm-desc: 92c94d0>
Ship it!Just look at C# or C++, both have at least an order of magnitude larger language “surface area”.
Also without the :: operator, it’s uglier than the arrow equivalent and it’s yet-another-construct to parse.
> There really aren't that many to learn.
I think there are a lot to learn in java ecosystem.
I think the closest thing is if someone would create linter for java which would allow only essential structures and library API. Java has very good foundational core.
obj match { case Point(x,y)=> println(x+y) }
Which probably explains the person saying "I hate it".
Destructuring for other kind of objects are planned with user-defined destructors. But it does have plenty prior art, e.g. in haskell you can deconstruct lists arbitrarily like _:secondElem:rest would bind secondElem logically.
if (obj instanceof Point p) {
System.out.println(p.x()+p.y());
}
But I can maybe see the value if you need to use x/y more than once.However in Java it's common to have getX() style accessors, for which this syntax doesn't seem that helpful as your variable would end up being called getX
That sounds like a deque, and it's been in Java for a long time. (No set or map implementations though.)
https://docs.oracle.com/en/java/javase/18/docs/api/java.base...
The only category I would say is objectively "better" is Java (and other JVM languages like Kotlin) has the best IDEs out of _any_ language. There is nothing on-par for Python, Ruby, C/Cpp, etc as far as autocompletion, type inference, automated refactoring, partial recompiles, hot code swapping, unit test integration, Tomcat or server integration, code formatting, etc. Java is great because of it's IDEs. If we were writing Java in notepad.exe it'd be a pretty clunky experience, but nobody serious does that.
Kotlin was made by the people behind IntelliJ. I'm not sure I understand your point.
Makes switching to vscode feeling going from an framing nailer to beating in rusty iron nails with a rock.
One feature that comes to mind is rearrange methods. I haven’t used Java in years so someone who actually uses both can find more cases where Kotlin support is worse than Java’s.
When targeting Java 8, Kotlin creates helper classes for the default methods on interfaces as that is not supported in Java 8, whereas on Java 9+ it uses Java default functions. However, you can target multiple Java versions, as I've done that with my projects for 11/17 support.
(Plus if you're going to go to the trouble of using a non-Java language it would be a real waste to use Kotlin over Scala)
I'm not sure that's a reason to pick Java over Kotlin though – streams are just generally cumbersome, even in Java, compared to Kotlin's sequences. By choosing Java you're getting more exposure to them whereas in Kotlin you can mostly avoid them in favor of sequences.
- Compile speed - Kotlin is still painfully slow - about 4-5 times slower than equivalent Java functionality (rough estimate)
- Kotlin is completely proprietary, no community or openness, no alternative to Jetbrain's IDE
- Kotlin (for me) has passed from being a simpler/more terse/attractive version of Java into being a complex language with lots of strange corner cases. Particularly largish Kotlin code-bases can be hell to read as Kotlin supports and encourages a DSL like approach.
For Android? Kotlin all the way.
Servers? Java is much closer to the JVM and Kotlin is an abstraction over it which honestly does not provide much extra compared to Java 21.
Kotlin has several design decisions which are neater 80% of time, but Java is the better general purpose language for those 20%. OC, much is a matter of taste. And in Kotlin will find yourself in awkward positions where you have to use Java Collections and you lose all the advantages of Kotlin (HashMaps not having non-nullable values is one of them).
Java has come a long way in recent years and it's far better than it was in the past. Kotlin stands on the great baseline of features that Java has established and there are certainly many advantages to (mostly ergonomics), to using Kotlin over Java at least for the time being.
<R> R collect (Supplier<R> supplier, BiConsumer<R, ? super T> accumulator, BiConsumer<R, R> combiner)
The fact that you see a type like Comparable<T> and can implement it with an anonymous function is unique to Java. In other languages you would have Function<Int, T, T> which simply baffles the mind. Java has a powerful and performant model which also benefits from static and default methods (e.g. functional composition).
Granted, the collect endpoint looks pretty wild but in 99% of cases you will simply use ".toList" or Collectors.toSet().
Not sure about that example since it’s easy to do
class MapWithDefault<K, V>(
private val map: Map<K, V>,
private val defaultValue: V
) {
fun get(k: K) = map.get(k) ?: defaultValue
// …
}
Edit: or I’m sure there’s something that does this already.When WebAssembly/gc becomes generally available, it will be exciting to see which languages will successfully target it. Kotlin has quite good chances of succeeding as a full-stack language, because of its growing ecosystem of multi-platform libraries that work in the JVM, in a browser, and on a native system. Note that the Java standard library is great, but it does not interoperate well with the JavaScript ecosystem. The same goes for C# and Rust.
As a personal pet project, and to check if the multi-platform concept actually works, I have written an emulator for an old computer in Kotlin. Initial development was done in the JVM, because I was familiar with JavaFX and sound output in Java. I then later compiled it to JavaScript, which was trivial and required no code changes, except for an implementation of canvas and audio rendering.
A serious problem is the IDE experience though. Interactive web development in VSCode with TypeScript is a breeze, with a subsecond edit-compile-run cycle. Kotlin compilation is still clunky, and fixing a typo requires at least 10 seconds of my patience, even on a decent workstation. Work is underway to improve this, but only time will tell if things succeed.
Or perhaps I'm missing some sarcasm here :)
Then there's other people like me who come from other ecosystems. I used to write Ruby and I just can't stand how verbose and convoluted Java can be. It makes reading code a real pain. But with Kotlin I found a language that struck a good balance between expressivity and compile-time safety.
Maybe Kotlin should do more to convert people from other ecosystems rather than trying to cater to the kinds of people who were never offended by the dullness of writing Java.
Also, all hail `val`; `final var` is objectively worse
That’s a feature, not a bug.
> We could eliminate suspend modifiers from pure-Kotlin code, but should we? I’m inclining to answer no. Having to mark asynchronous functions with suspend modifier is a small price to pay, but in return you get better insight into your code. You immediately see which functions are allowed to perform potentially long communications and which are supposed to complete quickly.
I'm not sure what's on the Kotlin roadmap / whether JetBrains see value in making major improvements to the language.
1) Cloud is better than data centers without sacrifices
2) Meal kits are better than grocery shopping without sacrifices
3) Online shopping is better than going to store without sacrifices
4) SAAS is better than locally installable software without sacrifices
I would not start Kotlin or learn it unless you go back 5 or more years.
The move from 8 to 11 was way harder than upgrading from 11 to anything else. In general Java compatibility between versions is very good.
Users can define their own template processors to control how the interpolation behaves: sanitize inputs, etc.
This part honestly seems like overengineering. Like Java architects resisted operator overloading for decades, and now they pull off this in the first version of templated strings ...
This has existed in JavaScript and Scala for years, and is a very useful feature.
Like for SQL queries:
sql`SELECT * FROM account WHERE name = ${name}`It's just really useful if you can have an API that can decide how interpolated stuff gets handled. You can santize, do custom formatting, lazy evaluation, all sorts of fun stuff.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
The new java way is strange, but maybe it was to avoid having to touch the language parser too much.
STR"x=\{x}"StringTemplate foo() { return RAW.""; }
is foo() == foo()?
This is a very useful feature of JS tagged template functions, as it lets a template processor do expensive one-time processing of a StringTemplate and cache the result, then use that to quickly apply that to particular values. I don't see an answer here: https://cr.openjdk.org/~jlaskey/templates/docs/api/java.base...
I’m tempted to pass the exam with Java 17, since the wait for Java 21 will be too long, assuming it will be several months after the GA date, September 21st.
The usefulness seemed to cut-off with Java 11 though and now the RS Java client is being deprecated.
We took way less time to move from Java 11 to 17 compare to the 8 -> 11 migration due to the change in deployment methods: instead of deploying jar file and run it with the server-provided JRE, we now use docker to ship our app + JRE to server.
Once your language has aged a little it's hard to impossible to take old primitives away, but you still want to adopt ergonomic improvements in order to not be left behind. Until at some point you become a language nobody can master in its entirety.
Laziness by default is my favorite Haskell feature.
Pretty poor tradeoff on the whole if you ask me - but Scala is always there for anyone with enough sense to pick it up.
"JDK21 is a version, for which many vendors offer support."
tl;dr: the Java version is not what gets "long-term support", it's a specific runtime JDK released by some Java vendor, e.g., Oracle, Eclipse Adoptium, Azul, Microsoft, Amazon (Coretto), etc.
Java's rocket sled continues to burn.
Rant:
JFC Java, its 2023 and people use Java to run actual databases and develop machine learning infrastructure. Yet the ability to do SIMD in the JVM is on its sixth incubation.
Even for native platform like C/C++ or Rust, SIMD intrinsic took a while to develop, and required multiple iterations to mature for each supported platform. Plus, with newer CPU instructions being introduced, the job is never fully done.
As noted in the JEP. The Vector API cannot be move to preview before value classes are available. Hence it is still in incubation and will be for quite some time.