News for hackers. Stuff that matters.
Re:JDK 15 by kentosi on Tuesday September 15, 2020 @11:37AM (#24482471)
I'm so happy that we finally have multiline text blocks in Java:

  String query = """
               SELECT "EMP_ID", "LAST_NAME" FROM "EMPLOYEE_TB"
               WHERE "CITY" = 'INDIANAPOLIS'
               ORDER BY "EMP_ID", "LAST_NAME";
               """;

It's one more step closer to scala/kotlin/etc.
Re:JDK 15 by 60secz on Tuesday September 15, 2020 @12:45PM (#24483357)
Shame they don't actually include templating inside of the string literal. Still have to append with a lot of tokenized replaces. Since they've committed to no formatting in the literal section, will be interesting to see if they eventually support a syntax like python's f-strings: f"""${foo}"""
Re:JDK 15 by carimura on Tuesday September 15, 2020 @12:50PM (#24483418)
Maybe you're looking for String::formatted?

Directly from http://openjdk.java.net/jeps/378:

  Another alternative involves the introduction of a new instance method, String::formatted, which could be used as follows:

  String source = """
                  public void print(%s object) {
                      System.out.println(Objects.toString(object));
                  }
                  """.formatted(type);
Re:JDK 15 by mumblemumble on Tuesday September 15, 2020 @01:06PM (#24483637)
I'd still prefer honest-to-goodness string interpolation. Formatting functions with positional placeholders need a linter to be kept (vaguely) maintainable, and I suspect that formatting functions with named placeholders would be difficult to make acceptably ergonomic or performant in Java.
Re:JDK 15 by thangalin on Tuesday September 15, 2020 @07:00PM (#24487705)
> I suspect that formatting functions with named placeholders would be difficult to make acceptably ergonomic or performant in Java

yamlp performs string interpolation from YAML files:

https://bitbucket.org/djarvis/yamlp/

I reuse my library in my text editor:

https://github.com/DaveJarvis/scrivenvar/

The text editor can interpolate strings in a variety of contexts (such as Markdown, R Markdown, XML, and R XML documents):

https://www.youtube.com/watch?v=u_dFd6UhdV8

As far as I can tell, there is no performance degradation from the recursive interpolation; the editor reads, interpolates key/value pairs, and substitutes the resulting values into R Markdown documents riddled with up to a thousand simple formulas in about 600 milliseconds (on my desktop computer).

Also, the editor provides a way to maintain the interpolated variables in a tree-like view:

https://github.com/DaveJarvis/scrivenvar/blob/master/README....

The substituted values appear in the preview pane in their final form. This is all real-time and pure Java.

Re:JDK 15 by oblio on Tuesday September 15, 2020 @02:56PM (#24485277)
Which one is easier to mess up and harder to debug afterwards?

A. "${label1} ${label2} ${label3} .... ${label 400}"

B. "%s %s %s ... %s".formatted(label1, label2, label23, ... label400) // Ooops, typo!

Re:JDK 15 by AnimalMuppet on Tuesday September 15, 2020 @02:58PM (#24485295)
For the particular typo you gave, it seems to me to be equally likely with either method.
Re:JDK 15 by oblio on Tuesday September 15, 2020 @03:34PM (#24485740)
I'll admit it wasn't the best example.

Here, have another one:

I want to have a string with this content:

"Fluffy Nero Polly<random text> ... <random text> Trexxie"

Which one is easier to figure out and debug?

A. "${cat} ${dog} ${bird} <random text> ... <random text> ${dinosaur}"

B "%s %s %s <random text> ... <random text> %s".formatted(dog, giraffe, dinosaur, ..., cat).

Re:JDK 15 by AnimalMuppet on Tuesday September 15, 2020 @03:45PM (#24485887)
Maybe A, but not (IMO) dramatically so. But shouldn't A actually be "${cat} ${dog} ${giraffe} <random text> ... <random text> ${dinosaur}"? That makes it closer in difficulty to B.

To me, the difference shows up more with this scenario:

A: "${v1} ${v2} ${v3} ${v4}"

B1: "%s %s %s %s".formatted(v1, v2, v3)

B2: "%s %s %s %s".formatted(v1, v2, v3, v4, v5)

B3: "%s %s %s".formatted(v1, v2, v3, v4)

A does what you tell it, whether it's wrong or right. B has a chance of warning you that the argument list and the format specifier don't match. On the other hand, B gives you two things that have to be kept in sync with each other, and A can't get out of sync, since there's only one thing.

So: Less of a chance to make the error, or more of a chance to catch it. Which is better? I lean toward A, but I will admit that it seems subjective.

Re:JDK 15 by RussianCow on Wednesday September 16, 2020 @02:26PM (#24495725)
> Less of a chance to make the error, or more of a chance to catch it.

B only catches mistakes in the case that the number of parameters doesn't match the number of placeholders, which isn't even possible with A. If the string you built isn't correct, that's on you in either case, and should be immediately obvious by looking at the output. So in that sense, interpolation is strictly better than `formatted` at dealing with potential mistakes.

Re:JDK 15 by Cthulhu_ on Wednesday September 16, 2020 @03:59AM (#24490512)
Go doesn't have interpolated strings but printf / sprintf and co, and its compiler will warn and error if your arguments do not line up or have the wrong type.

I mean it's not ideal, but sprintf and co are only intended for relatively short text (like logging), if you have any more, use a templating language instead. Plenty of those in Java as well (JSP, Velocity, etc).

Re:JDK 15 by dtech on Tuesday September 15, 2020 @01:02PM (#24483594)
This was already there, and is much less user-friendly than string interpolation, because it's easy to mess up order
Re:JDK 15 by johnnycerberus on Tuesday September 15, 2020 @12:48PM (#24483403)
http://manifold.systems/ has a Java template engine that can be helpful
Re:JDK 15 by 60secz on Wednesday September 23, 2020 @10:14AM (#24567308)
Will definitely check it out!
Re:JDK 15 by mckinney on Wednesday September 16, 2020 @04:29AM (#24490685)
The Manifold project[1] provides string interpolation for Java. You enable it as a Java compiler plugin, it's pretty cool.

[1] https://github.com/manifold-systems/manifold/tree/master/man...

Re:JDK 15 by dtech on Wednesday September 16, 2020 @06:51AM (#24491358)
while cool, it's pretty telling that similarly high-level languages like C#, Kotlin, Scala, Python, Swift and Javascript have had this widely-used quality of life for years while Java doesn't
Re:JDK 15 by carimura on Friday September 18, 2020 @11:10AM (#24517744)
And by telling I think you mean that over time Java has very thoughtfully evolved in a way that respects backwards compatibility, or that once a feature is in the language it'll very likely stay there for the next 25 years. Yes, innovation is very important (and happening faster than ever now with the 6-month release cadence), but a majority of the work isn't in deciding what goes in, it's deciding what stays out and if something does go in how does it satisfy both audiences of "move slow don't break" and "move faster we want features".

A good video on this process: https://www.youtube.com/watch?v=2y5Pv4yN0b0

Re:JDK 15 by 60secz on Wednesday September 23, 2020 @10:14AM (#24567306)
Thanks. Looks very interesting
Re:JDK 15 by zelly on Tuesday September 15, 2020 @01:14PM (#24483766)
I'm glad Java is being conservative and not doing that. JS/Python f-strings have not proven themselves long-term. It also bloats the language with yet another mini-DSL. You can always add a proper templating engine on top.
Re:JDK 15 by bad_user on Tuesday September 15, 2020 @01:43PM (#24484200)
Java relies on String + Object for composing strings, thus unsafely converting any object into string. An implicit conversion, akin to what JavaScript is doing.

String interpolation would be safer, as it would make the intent clearer, and you wouldn't risk bumping in corner cases. It would be even safer if the protocol could be overrided such that you wouldn't have to use Object#toString, but for Java that's too much already.

Java has been a very conservative language. And I understand why.

But it's funny how, for many features that were added later, people were rationalizing their absence with such lines too. E.g. we don't need anonymous functions / lambdas, as anonymous classes are enough. Well, turned out that Microsoft was right all along when they released those in J#.

Also adding a template engine is overkill for doing string concatenation.

Re:JDK 15 by zelly on Tuesday September 15, 2020 @03:00PM (#24485316)
> But it's funny how, for many features that were added later, people were rationalizing their absence with such lines too

There's nothing wrong with that. If string interpolation is really useful, then Java will add it some years down the line.

It's cheap to add features but literally impossible to remove them. There's no way to undo a mistake in language design. That's an asymmetry. I'd rather err on the side of caution than kitchen-sinking it.

Re:JDK 15 by bad_user on Wednesday September 16, 2020 @12:43AM (#24489602)
Oh, I don't know about that. I wouldn't call it impossible.

I like how Java binaries still work on the latest Java, however, if distribution happens via binaries, why should the language keep source compatibility anyway?

Or, you know, the latest compiler could allow you to select the source code version you want. And automated code migration tools can work too.

---

Err'ing on the side of not getting features is why Java has lost a lot of mindshare.

Java is still super popular, but that's basically in spite of the language itself, because the language is awful.

Re:JDK 15 by fomine3 on Thursday September 17, 2020 @08:28PM (#24511635)
> If string interpolation is really useful, then Java will add it some years down the line.

Now is the year. String interpolation is really harmless feature.

Re:JDK 15 by 60secz on Wednesday September 23, 2020 @10:06AM (#24567202)
It deeply pains me that String is only a concrete type and that Object.toString() does not implement an interface.
Re:JDK 15 by pjmlp on Tuesday September 15, 2020 @04:34PM (#24486390)
J++, J# was as transition into .NET.
Re:JDK 15 by bad_user on Wednesday September 16, 2020 @12:45AM (#24489610)
Indeed, you're correct.
Re:JDK 15 by Drdrdrq on Tuesday September 15, 2020 @02:59PM (#24485307)
> JS/Python f-strings have not proven themselves long-term.

Are you saying that they haven't been around for long or that they failed? If latter, then I respectfully disagree. Any recent JS and Python code I have seen uses them extensively. They are also a joy to use, and imho improve readability immensely. Ergonomics matter. This is one aspect of Python3 I would miss the most if I had to go back to 2.

Re:JDK 15 by oblio on Tuesday September 15, 2020 @02:58PM (#24485288)
Conservative? We've had "f-strings" since 1979, at least.
Re:JDK 15 by CydeWeys on Tuesday September 15, 2020 @03:08PM (#24485428)
The ones in Python work significantly differently though; they have inline code execution (rather than using a varargs list after the f-string itself).
Re:JDK 15 by mixmastamyk on Tuesday September 15, 2020 @03:26PM (#24485647)
So does shell script and several modern programming langs. The sky hasn't yet fallen.
Re:JDK 15 by danudey on Tuesday September 15, 2020 @05:58PM (#24487219)
The Bourne shell had parameter expansion in strings in 1979, just FYI.
Re:JDK 15 by oblio on Tuesday September 15, 2020 @03:32PM (#24485723)
I've just executed:

echo "$(ls)"

in my zsh, so I'm not sure what to say, to be honest.

Re:JDK 15 by danudey on Tuesday September 15, 2020 @05:57PM (#24487207)
Closer to:

echo "Username is ${USER}"

As I recall (and Wikipedia seems to confirm), parameter substitutions were in the original bourne shell in 1979, so... Yeah, I'm not sure what's going on there.

Re:JDK 15 by jen20 on Tuesday September 15, 2020 @12:08PM (#24482903)
Does this result in a string with a hanging indent, or is the common prefix removed?

(Sorry, being somewhat lazy, I could pull up the spec).

Re:JDK 15 by curtis3389 on Tuesday September 15, 2020 @12:18PM (#24483036)
The common prefix is removed:

> Incidental white space surrounding the content, introduced to match the indentation of Java source code, is removed.

Re:JDK 15 by hashhar on Tuesday September 15, 2020 @12:34PM (#24483236)
I hate such kind of magic. Very convenient at first but can cause countless hours spent on debugging in some cases.

I like how Scala does this via the indent marker and strip.

Re:JDK 15 by e12e on Tuesday September 15, 2020 @12:42PM (#24483327)
I was going to answer gp "probably not" - but I would've been wrong. It looks to me like Java now has some of the most sophisticated in-line multi-line strings/here-documents that I'm aware of in any language. More details in:

https://openjdk.java.net/jeps/378

I'm not entirely sure "most sophisticated" is entirely a good thing - but the jep looks pretty thorough at least.

Ed: how does Scala do it? Java uses the indents for the closing triple-quote to determine stripping/indent + cutting trailing spaces. Ie, if my reading is correct:

  a = """
         OK.
      """
Is "OK.\n" (even if there are any spaces after the dot).
Re:JDK 15 by chadrs on Tuesday September 15, 2020 @01:15PM (#24483781)
At the string literal level doesn't do anything, but the standard library adds an extension method to string called `stripMargin`. This has some nice examples https://www.oreilly.com/library/view/scala-cookbook/97814493...
Re:JDK 15 by electrum on Tuesday September 15, 2020 @01:25PM (#24483959)
The indentation is removed at compile time, per the JLS: https://docs.oracle.com/javase/specs/jls/se15/html/jls-3.htm...

> Incidental white space is removed, as if by execution of String.stripIndent on the characters resulting from step 1.

The new stripIndent() method is provided as a convenience to developers.

Re:JDK 15 by Nullabillity on Tuesday September 15, 2020 @01:34PM (#24484086)
That's for Java, the parent is talking about Scala.
Re:JDK 15 by CydeWeys on Tuesday September 15, 2020 @03:12PM (#24485471)
It helps that Java is exclusively a compiled programming language, so these are just syntactic sugar concerns for the parser/lexer and the compiled bytecode ends up looking identical to having just used one long string with inline \n.

So given that, I don't think it really ends up being that sophisticated. I think this could be a decent easy programming question for a technical interview though!

Re:JDK 15 by dfinninger on Tuesday September 15, 2020 @01:34PM (#24484095)
I had to use this recently for an online course. It was super nice:

  def pushConstant(num: Int): String =
    s"""
       |@$num
       |D=A
       |$accessTopOfStack
       |M=D
       |$incrementStackPointer
       |""".stripMargin
accessTopOfStack and incrementStackPointer are other functions that return text. It made composing Assembly a breeze.
Re:JDK 15 by rad_gruchalski on Tuesday September 15, 2020 @05:29PM (#24486910)
Yup, and it’s super nice for json or yaml strings.
Re:JDK 15 by electrum on Tuesday September 15, 2020 @01:18PM (#24483831)
IntelliJ shows you exactly where the block starts, so if you have a line with less indentation (causing the entire block to start at that column), it is easy to spot.
Re:JDK 15 by hashhar on Wednesday September 16, 2020 @12:07PM (#24493976)
Thanks for sharing that. I can definitely see myself using the multi-line blocks since they are much better than the kind of things we need to do today.

At the same time I'm slightly scared of that magic. It helps that it's well-defined in the JEP.

Re:JDK 15 by jen20 on Tuesday September 15, 2020 @05:19PM (#24486823)
Thanks, quote much appreciated!
Re:JDK 15 by jsumrall on Tuesday September 15, 2020 @05:48PM (#24487114)
If you’re writing code like this I can highly recommend http://www.jooq.org/
Re:JDK 15 by agumonkey on Tuesday September 15, 2020 @02:45PM (#24485090)
and closer to humans
Re:JDK 15 by dxxvi on Tuesday September 15, 2020 @05:48PM (#24487109)
I'm waiting for Try and Either in Java. Multiline text blocks are good but not enough.
Re:JDK 15 by kelnos on Tuesday September 15, 2020 @07:03PM (#24487726)
If you want those, you can use Vavr[0].

Ultimately the issue isn't the presence or absence of those classes (because they aren't hard to write minimal versions of as a one-off if you need them and can't allow the dependency), it's the pervasiveness of use (or lack thereof) by libraries and especially the standard library.

If Try and Either were added to the Java stdlib tomorrow, the rest of the stdlib would still be stuck throwing exceptions for error propagation, because they can't change the return types of existing methods. The only benefit would be that third-party libraries could feel comfortable enough to use them in their type signatures. But, in practice, most libraries still target Java 8, so I wouldn't hold my breath for that, either.

[0] https://vavr.io

Re:JDK 15 by johnnycerberus on Tuesday September 15, 2020 @12:59PM (#24483563)
I think we can do better than Java, Scala and Kotlin. All of these ended up to be piles of abstractions and complexity. Scala went too hardcore for somebody that just wants to deliver. Kotlin gives you anxiety everytime they push for supporting a new platform. Java, though it is still nice, has accumulated too much cruft during the years. I wish for a Go-like language on the JVM. A modern language that offers you a minimum number of features from which you can build upon. Moreover, lower, well-thought out abstractions would give a boost in perfomance with the new garbage collectors that have been added in the JVM. I can imagine Clojure is something that I would like to try again sometimes, but the fact that it is a LISP and lacks even simple types make it less attractive to the majority of devs. Also, Clojure wouldn't be my choice for high-perfomance if I want to do mostly imperative stuff.
Re:JDK 15 by weego on Tuesday September 15, 2020 @01:10PM (#24483703)
Scala is perfect for just delivering, myself and my business partner have been using it to rapidly prototype and build for a decade now. You just avoid all the stuff that tries to make scala into haskell and use it as the hybrid OO/functional language is was designed as.
Re:JDK 15 by johnnycerberus on Tuesday September 15, 2020 @01:24PM (#24483943)
You're lucky that you can do that kind of work. I've been working for a state company in Bulgaria and we had to maintain some Scala pipelines built with Apache Spark some years ago. It wasn't a pleasant experience, just a sea of vars/vals and cases of reinventing the wheel only to use some functional constructs when it could be simply done in Java by just adding a dependency that has already solved that problem like 10 years ago. It wasn't even some complicated logic in that, just calling different APIs and playing with dataframes, but the fact that they hid from me so much behavior only to reduce verbosity gave me some stressful days.
Re:JDK 15 by non-entity on Tuesday September 15, 2020 @02:18PM (#24484696)
Any partitular reason scala was chosen? Spark has Python and Java API's as well.
Re:JDK 15 by rad_gruchalski on Tuesday September 15, 2020 @05:30PM (#24486936)
Why not use that java dependency in scala?
Re:JDK 15 by eitland on Tuesday September 15, 2020 @10:39PM (#24489036)
Culture it seems.

Functional style is cool and some people will go to great lengths to use it.

Like shaving a few characters of a perfectly fine piece of code by using currying and instead make one single long line of code describing it.

Re:JDK 15 by pjmlp on Wednesday September 16, 2020 @03:36AM (#24490380)
Guest language syndrome. All libraries must be idiomatic instead of reusing the platform language based libraries.
Re:JDK 15 by johnnycerberus on Wednesday September 16, 2020 @04:16AM (#24490615)
Exactly that.
Re:JDK 15 by Erlich_Bachman on Tuesday September 15, 2020 @03:12PM (#24485465)
Use Groovy.
Re:JDK 15 by mathh on Tuesday September 15, 2020 @04:03PM (#24486102)
+1 to Groovy.

Can be very simple and elegant, like a better Python, on the JVM.

But also very rigorous, as a Java superset, with powerful features like mixing dynamic and static compilation in the same class.

Or even deep, with run-time metaprogramming and compile-time AST manipulation capabilities (giving tools like Gradle, Spock...).

And you have of course multiline interpolated Strings. And so much.

Re:JDK 15 by danudey on Tuesday September 15, 2020 @06:03PM (#24487272)
I've been using Groovy extensively to script and automate inside of Jenkins, and hoo boy it's actually kinda nice.

My absolute favorite thing is being able to do something like:

    someIntegerCollection = someStringCollection*.toInteger()
I also find the use of closures for things like collection filtering to be quite nice:

    canadianUsers = someUserCollection.findAll { user ->
      user.countryCode = "CA"
    }
The equivalent in Python is a little more cumbersome and overly verbose:

    canadianUsers = [user for user in someUserCollection if user.countrycode = "CA"]
I'll still be writing things in Python whenever I can, but when I do write in Groovy there's a lot of nice stuff I get to have.
Re:JDK 15 by Erlich_Bachman on Wednesday September 16, 2020 @02:40AM (#24490129)
And if you need it, static typing is one annotation away... This is such an underestimated feature. While prototyping it might be easier to use dynamic typing, but once a project becomes complex and has more people working on it etc, - you might want to switch it to statically-typed. Groovy simplifies this immensely and minimizes the amount of code that needs to rewritten.
Re:JDK 15 by johnnycerberus on Tuesday September 15, 2020 @03:59PM (#24486040)
I guess that is the stack behind the great Aviato? Groovy from back to front.
Re:JDK 15 by cmrdporcupine on Tuesday September 15, 2020 @06:09PM (#24487313)
I'd be good with TypeScript running on the JVM, even.