
Kotlin vs. Java - driver733
https://www.kotlinvsjava.com
======
JanecekPetr
The I/O example is moot since Java 11 where Java got
[https://docs.oracle.com/en/java/javase/13/docs/api/java.base...](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/nio/file/Files.html#readString\(java.nio.file.Path\)),
so we can do `Files.readString(Paths.get(doc.txt))`.

Java 14 is getting an experimental preview of Records
([https://openjdk.java.net/jeps/359](https://openjdk.java.net/jeps/359)) which
takes care of much (but not all) of ceremony around "data classes".

And Java 13 got a preview of text blocks,
[https://openjdk.java.net/jeps/355](https://openjdk.java.net/jeps/355).

Things are coming. That said, I hardly believe those minor syntax improvements
are what is so "good" about Kotlin. It has some better defaults (non-null by
default, final classes by default), and is a more modern language. Java will
stay with us for many years to come, though.

~~~
guelo
I wonder if Java's speeding up of new language features over the past several
years, after many years of a stagnant feature set, is a direct result of
pressure from the likes of kotlin.

~~~
_akei
It is mostly C# that is keeping Java on their toes. Java competes with C# than
any other language in this world. In the enterprise space, it is either Java
or C#. If you check most of their improvements, they were done ion C# first,
then they follow.

~~~
guelo
kotlin copied a lot from C# first.

~~~
madiathomas
Now that is a good strategy. Copy directly from a language that is moving at a
very fast pace and competing directly with the language you want to replace.

~~~
pjmlp
Kotlin will never replace Java, unless you are speaking about Android Java.

~~~
byte1918
Of course it won't ever replace it but it has the potential to overtake it.

~~~
pjmlp
Maybe when I see the first JVM written in Kotlin I will consider that
scenario.

Even considering ART as the KVM, isn't a safe deal, as it is written in a mix
of Android Java and C++.

And currently its potential is very tiny when measuring all JVM guest
languages against Java, using any recent language report.

------
m23khan
Frankly, I find Kotlin syntax a lot more meaningful as it contains much less
boilerplate code than Java. And the same time, though, I believe Kotlin can
only be truly appreciated if you are coming in from experience with Java.

The thing I found hard at times with Kotlin is that it allows/relies on Java
classes/frameworks but almost all of those classes/frameworks have their
documentation (and only resources) written in Java so you have to have that
additional mental step of translation between the two languages.

If you are not competent with basic Java, you may struggle to utilize those
Java classes in Kotlin effectively.

Finally, when it comes to hiring people/finding job for Kotlin development,
outside of Android jobs, there are very few positions requiring Kotlin which
in terms means that there are very few non-mobile developers working with
Kotlin as compared to Java. Now this may not be that much of a concern to us
Developers, but for Management and leadership, it can raise a big concern
towards adopting a language which from perspective of labor market comes
across as a niche.

Having said all this though, I have no doubt at least in Android development,
Kotlin will replace Java as programming language of choice but I don't think
it will find traction beyond mobile (to displace / challenge Java).

~~~
gentaro_
I think I can confirm your sentiment. As far as I can tell, which, however, is
not much as pertains to the JVM, apart from polyglot projects, Kotlin is a
rarity.

I'm rather unfamiliar with Kotlin as a language. Is Kotlin for Android rather
idiosyncratic as is Android Java? In other words, is there a superset of
language features in Kotlin that goes beyond Android and is more expressive
than modern Java?

~~~
thu2111
It's actually not that rare, in my experience. Job adverts can be quite
misleading in this case. Kotlin jobs are usually advertised as Java jobs. For
a couple of reasons:

Firstly, quite a few large shops have started to use it, but usually due to
grassroots bottoms-up activity of the sort that takes a while to percolate
through to recruiting departments in distant departments where changing a job
req is a heavy process.

Secondly, there's really not much incentive to try and change job reqs like
that because it would be extremely hard to advertise via job reqs _We use
Kotlin but you don 't have to know it to apply_. To a non-technical recruiter
or HR department this looks like a useless statement and will frequently get
"fixed" to what you "really meant", something like "Java experience is
required, Kotlin highly desirable" which might just put off candidates who
don't know what Kotlin is or how easy it is to learn. You're just restricting
your pool of candidates for no reason in a highly competitive market.

Much better to advertise the usage of Kotlin in places where developers
looking for new opportunities might notice and leave the job reqs alone, and
let Java devs get up to speed in the first few days. For example:

[https://medium.com/ing-blog/introducing-kotlin-at-ing-a-
long...](https://medium.com/ing-blog/introducing-kotlin-at-ing-a-long-but-
rewarding-story-1bfcd3dc8da0)

 _Edit:_ To answer your later question, yes, Kotlin goes beyond Java in a lot
of ways other than nicer syntax. For instance it has a different (better)
generics model, it has far more type inference, it has sealed (sum) types, it
has language-integrated coroutines, it has compiler plugins that automate,
amongst other things, serialization, it has delegated properties and
interfaces, it has type aliases, it has extension functions etc.

I suppose a lot of these can be considered "just" better syntax than Java
(except for coroutines and generics), but, at the heart of most programming
languages is making patterns that are possible in other languages much easier.

------
jeroenhd
Why don't the nullability examples use Java's Optional?

This code:

    
    
      if (nullableVariable != null) {
          boolean success = nullableVariable.someMethodCall()
          if (success) {
              return success
          } else {
              return fallbackIfNullMethodCall()
          }
      } else {
          return fallbackIfNullMethodCall()
      }
    
    

Could also be written something like this:

    
    
      result = Optional.ofNullable(nullableVariable)
                       .map(NullableType::someMethodCall)
                       .orElse(fallbackIfNullMethodCall());
    

Sure, it's no Elvis operator, but it's a lot more readable than the "standard"
if/else structure of traditional Java. If we're comparing Java and Kotlin, we
should at least give Java a fair chance. I dislike the verbosity of the
Optional wrapper, but it's a lot better than if/else checking.

~~~
rococode
Even the simple if/else approach can be done more cleanly (i.e. without
repeating the fallback call):

    
    
      boolean success = false;
      if (nullableVariable != null) {
          success = nullableVariable.someMethodCall();
      }
      if (success) {
          return success;
      } else {
          return fallbackIfNullMethodCall();
      }

~~~
arnvidr
Even that seems way too much. The original would be much easier as:

    
    
      if (nullableVariable != null) {
          boolean success = nullableVariable.someMethodCall()
          if (success) {
              return success;
          }
      }
      return fallbackIfNullMethodCall();
    

And even that can be more concise if you prefer:

    
    
      if (nullableVariable != null && nullableVariable.someMethodCall()) {
          return true;
      }
      return fallbackIfNullMethodCall();

------
nostrademons
This doesn't really showcase many of the best advantages of Kotlin. They
should add some with data classes, JavaBeans, multiple assignment, lambdas,
map/reduce/fold, extension methods, etc. I've found that Kotlin code is
usually 3-4x more concise than Java, and most of the benefit is in your data
structure definitions (i.e. changing 100 lines of boilerplate to a 4-line data
class, or destructuring a Pair/Triple where you would otherwise have been
tempted to create a new class and 2-3 lines of assignments) rather than in
individual statements.

~~~
commandlinefan
Kotlin (which I don't know) looks a lot like Scala (which I do), at least
superficially. Wonder if you've had any experience with Scala to compare the
two?

~~~
tlarkworthy
I did Scala first, then recently took over a codebase with both. I think the
people who did Scala were not good and they made a total mess, however, their
Kotlin miscroservice was actually quite nice and was the best code in the
project. So I reluctantly have concluded Kotlin is a better level of
expressivity. Scala is full of footguns... I love it ... but it's hard to
write well.

One example was they were using enumerations and got boxed in. They had to add
unit tests to ensure they enumerated all the options. Why does Scala have that
feature? It's full of bad features you should avoid.

~~~
cryptos
I have the same experience. Once you do more with Scala than "better Java" it
is easy to create a mess full of "try to be clever" code you will regret a
year later.

It is really hard to become a good Scala programmer, but it is not hard to
become a good Kotlin programmer. All the little things that make Scala
theoretically better are not worth the learning effort. In Kotlin you get 80 %
for 20 % of the effort.

Scala is separated in subcultures. Some developers use it as "Haskell for the
JVM" and other as a "better Java", or something between. That makes hiring and
picking up existing projects hard.

Tooling is another weakness of Scala. Scala IDE (Eclipse) is more or less
dead. IntelliJ with the Scala plug-in is ok, but the Kotlin support is much
better.

------
tdelev
I have been extensively programming in Kotlin in the last 2 years coming from
a 10 years Java experience. Even Java advanced a lot from from version 8,
still it is very far behind in reaching the pure joy of programing in Kotlin,
especially in functional style. Immutability with 'val', data classes,
functions as first class citizens, destructuring, if/when expressions, just to
name a few of the features than enables this.

Also, the great 100% interoperability with Java makes possible to migrate part
of your codebase to Kotlin and using tons of already proven and great
libraries in the Java ecosystem. On top of the Kotlin standard library
includes many improvements of the existing Java classes from collections to
String, and all of this using extension functions, one very usefull and
powerful feature.

I can keep going on and on, but to conclude Kotlin is not just Java with
improved syntax, but completely new modern programming language incorporating
or "borrowing" some of the best features from Scala, C# and other popular
programming languages. So in my opinion it is a great language which has a lot
more funtional features than Java, but still pragmatic and easier to learn
than Scala.

~~~
pjmlp
There is no 100% interoperability with Java.

Try to call co-routines from Java, use SAM types with default methods from
Kotlin, just for starters.

~~~
tdelev
I was mostly referring to the Kotlin calling side of Java code and libraries,
and yes you're technically right that would mean only 100% compatibility with
existing Java code and not interoperability. But, when moving forward to using
exclusively Kotlin and not building libraries that will be Java compatible
that is totally ok.

~~~
pjmlp
Kotlin is not moving forward on the JVM given that the platform is written in
Java, and Kotlin happens to be a guest language, now with JetBrains trying to
build a Kotlin platform.

------
soulnothing
At it's base Kotlin is a nicer java. But it's much more. Simply looking at the
syntax comparison is only half of the story. The focus at the recent
conference was multi platform and concurrency.

They are making concurrency a first class citizen. With items like Go
channels, Observable etc. This is baked into the language. There are a number
of new frameworks utilizing these patterns. Resulting in less code, and more
performance. At the cost of sometimes more difficult debugging.

The bigger item to me is multi platform. I'm working on a micro orm. That
reflects your schema automatically generating types for NodeJs, Native, and
JVM(Graal/JDK). It can then be run on any of those platforms. An example is
libpq for postgres allows streaming and observing rows on update. This is not
in the DB libraries that I've seen yet. I can have an actor run natively on
LLVM, talk back via grpc/rsocket/tcp/etc. To a JVM/JS service. All while
adhering to the same interface / method description.

Besides that. There are scripts for kubernetes, react/angular/vue, etc. Dukat
is coming to automatically convert ts.d files to kotlin description files. For
me I can have one language, one IDE, for every part of my product. From
deployment, back end, data handling, front end, and mobile.

~~~
vips7L
I don't see how concurrency isn't a first class citizen in Java, especially
compared to kotlin/native's concurrency package which is barely a package.

~~~
fnord123
Thread based concurrency where everything is blocking inside the thread is the
first class citizen. If you want to move to a non blocking world, then you
will suffer.

Moving between Channel and Flow sucks. No async/await keywords like Python,
C#, Rust so you have callback hell. try-with-resources doesn't work with async
callbacks (i.e. thenApply, thenCompose, etc.).

Also, JAX-WS standard doesn't currently support Channel or
Publisher<ByteBuffer> for body types.

~~~
apta
Java is getting green threads/fibers by means of project Loom. Arguably much
more straightforward to use compared to async/await.

~~~
ksec
So when is this Project Loom set to arrive?

~~~
fnord123
Literally "when it's done". This is the answer given in talks by the
developers working on it.

But you have to understand that many many libraries are on Java 1.8 because
that's what Android supports. Even when Loom arrives, many libraries won't use
it but will rather continue to use threads.

~~~
thu2111
But that's the nice thing about Loom. The direction they're heading in is
upgrading the existing Java threading APIs. Maybe not "new Thread() {}" but if
you use ForkJoinPool, executors, etc then it should mostly all just work. That
means it won't fork the ecosystem in the same way Kotlin coroutines do
(coloured functions in new languages). And even better it won't fork the
ecosystem across Android either. If you use constructs that don't
automatically Loomify, you can just tweak them so they still work fine on
Android but get the benefits of Loom too.

BTW parts of Loom already shipped.

On the other hand, outside of certain core libraries this won't matter much.
You don't do a whole lot of scalable blocking IO on phones.

~~~
fnord123
>Maybe not "new Thread() {}" but if you use ForkJoinPool, executors, etc then
it should mostly all just work.

Ah that's a nice way to do it. But then what happens to Channels? Are they
cast aside so we go back to InputStream which blocks the fiber?

> You don't do a whole lot of scalable blocking IO on phones.

No but you can save a lot of memory, a lot of context switches, and CPU
depending on the scenario.

~~~
thu2111
I'm not sure but yeah, in theory you don't need more than Input/OutputStreams
if you can block at will.

------
_akei
Whenever I see an article comparing a market leader with an underdog, I always
know that the article will be biased against the market leader. It is human
nature to root for the underdog. What was the reason for not starting with
variables II? I suspect the author wanted to manipulate our minds right there.
It is obvious that Java version is the better of the two but they decided to
start with a variable with final. Ternary operator for Kotlin doesn't look
like ternary to me. It is just an inline if\else.

~~~
Jataman606
Why is variables II better in Java? Its almost the same with advantage on
Kotlin side with type inference. Also ternary operator isnt needed in Kotlin
since if/else itself can return value, so its just example to show so people
dont try to look for it in Kotlin. Overall its not even an article, its just a
showcase of differences in syntax and idioms in both languages, i cant fathom
how could you be manipulated with that.

~~~
madiathomas
Clear and concise to someone new to programming. Also less typing. Comparison
of an a market leader to a new entrant is designed to make you switch from
market leader to new entrant in the market.

------
xwowsersx
Comparing to

>>> public static void main(final String[] args) { System.out.println("Hello
world!") }

Is just a glamour shot. How many times does one actually have to type public
static void main? Once per application, by definition.

~~~
sansnomme
Isn't final optional?

~~~
saagarjha
Yes. And there are cases where omitting it is specifically useful.

------
ulrikrasmussen
Kotlin is much nicer than Java, that's for sure. It strives to be compatible
both ways (calling Java from Kotlin and vice versa), which I think has helped
with its adoption. It also means that it cannot have very wild features that
can't be mapped nicely to the world of Java, which I think has its downsides.

My main gripe with Kotlin is some of its design choices for syntax. I really
really really don't like its syntax for lambdas, specifically. A code block in
curly braces could be both a lambda with an implicit argument, or a list of
statements. You have to inspect the context to see which one it is, or rely on
intelliJ to make the former type slightly bolder. That is so bad for
comprehension, and I think the only reason it was done like that was to allow
for some cute hacks where control flow constructs such as map, fold etc. could
be implemented using lambdas and still look like regular imperative code.

Another thing is that you can create lambdas with an implicit binder that you
can refer to as "it" inside the body. It may save you one or two keystrokes,
but it also encourages the programmer to be lazy about naming things. Combined
with the fact that curly braces are overloaded, whenever I see "it" in code,
my eyes scan frantically for the first opening curly brace, and I then have to
determine whether it is a lambda with an explicit binder (then it isn't my
binder, and I have to continue searching), a statement block (then it also
isn't my binder), or a lambda with an implicit binder. Don't get me started on
nested lambdas with implicit "it" binders that shadow each other.

~~~
thu2111
Well, they see it more as a core language feature than a cute hack. Kotlin 1.0
was big into DSLs as a competitive advantage, though I don't think it got
adopted in the way they hoped and I don't see much talk about it anymore. But
the idea was you can make libraries where you can write code like this:

    
    
        val page = html {
            head { title = "Title" }
            body {
               etc
            }
        }
    

It looks like it's a part of the language and naturally integrates with
features like code folding, but it's actually all just functions and objects
anyone can create.

DSLs _have_ taken off in one area: UI construction. There's TornadoFX for
JavaFX, SwiftUI on Apple and JetPack Compose for Android. I've tried both new
and old approaches extensively and to be honest I'm not sure this is actually
better than using a proper GUI builder, but for small fragments of UI it's
pretty neat. Sort of like what JSX does in React but more principled and type
safe.

~~~
ulrikrasmussen
I don't see why you can't create DSLs with an equally compact syntax which
doesn't overload the curly braces. Yes, it would look different, but it would
be more readable. Curly brace lambdas give a first impression of readability,
but they really are not when you consider how they affect the binding
structure.

------
psychoslave
Not to defend Java, but some examples seem just unfair:

    
    
        if (nullableVariable != null) {
            boolean success = nullableVariable.someMethodCall()
            if (success) {
                return success
            } else {
                return fallbackIfNullMethodCall()
            }
        } else {
            return fallbackIfNullMethodCall()
        }
    
        // Wouldn't that work just as well ?
        if (nullableVariable != null) {
          return nullableVariable.someMethodCall() || fallbackIfNullMethodCall();
        }
        return fallbackIfNullMethodCall();
    
    
    

Ok, that is still more cluter than the kotlin elvis operator, but more fair,
isn't it?

~~~
RyEgswuCsn
Would this work?

    
    
      return Optional.ofNullable(nullableVariable).map(v -> v.someMethodCall()).orElse(false) ? true : fallbackIfNullMethodCall();

~~~
AnyTimeTraveler
Why not replace the tenary operator at the end with the method call in the or
else block?

return Optional.ofNullable(nullableVariable) .map(v::someMethodCall)
.orElse(fallbackIfNullMethodCall);

That also looks much easier to understand, at least to me.

------
findjashua
the biggest wins w Kotlin, imo, are the sensible defaults - variables are non-
nullable & collections are immutable by default. These eliminate entire
classes of runtime exceptions and bugs (respectively).

------
jermaustin1
I don't know if I like the "Elvis Operator" \- I feel its one too many
conditions on a single line.

And the ternary operator is just odd when there is a more terse "standard"
approach to it.

~~~
dajohnson89
It feels like a common sentiment that concise code == good code

~~~
driver733
To be more precise, I would say that expressive code == good code

~~~
martin1975
As long as expressive doesn't mean too terse and somewhat readable to
most...lest you commit perl's sins.

~~~
dajohnson89
Yeah. This was the point I was halfheartedly making -- concise code for the
sake of concise code is a dogma that needs to go away.

------
thom
There are very few of these examples that don't just make me feel exhausted
compared to the Clojure version, but I realise it's a different set of
priorities entirely.

------
ulkesh
I love the idea and look/feel of Kotlin. I work to learn and use it on my own.

In the workplace, however, the problem for me are the fearful developers who
think it is too difficult to maintain a multi-project code base that contains
more than one language. I want to continually grow and improve and branch out,
sadly I find many I work with who would rather just skate by on what they know
(in this case, Java, which I helped to mentor).

I haven’t yet found a way to convince them. I feel the only way I’ll be able
to use Kotlin within the workplace is by changing jobs.

Java is still a great language, and the new release model is helpful to get
some of the more modern language features found in other languages sooner in
the Java ecosystem. And while JEP is a fine governance model for feature
development, I still find myself wanting more, sooner, than what it produces.

I welcome any thoughts or suggestions on how to convince others of the
usefulness of introducing Kotlin into the workflow. The idea I attempted was
that I would begin a new project with Kotlin that, to start, only I maintained
— to make it easier for others to begin to absorb the language, at their own
pace. It was futile and they simply don’t want to try.

~~~
wippler
I don’t know why but your assumption that others are skating by with what they
know rubbed me the wrong way (maybe because I have been on other side of
this). There are likely many other valid reasons here - project deadlines
(sometimes it is not the right time to pick a new language), consistency of
code (having a mix of languages is going to raise hell in code reviews with
opinions on some code that could be done better in one language vs other),
hiring (does your hiring/onboarding get more complex?), writing idiomatic code
(learning a new programming language is easy but writing good code is hard),
extreme swing in brevity (people abusing new languages to write concise code
using obscure language features, which makes it hard for someone new to jump
in).

I am sorry I don’t have any suggestions to fix your problem but I just wanted
to provide a bit of perspective. Maybe try thinking from your peers
perspective to see what benefits adopting this new language would give and be
prepared to answer why Kotlin among a whole class of JVM languages - Scala,
Kotlin, Groovy, Clojure.

~~~
ulkesh
It’s a very small company and I’m the lead developer. I know exactly what is
being worked on and what timelines are involved. The replies I got when I
suggested all of this was something akin to “Why now and not before? Why this
project and not the others?” Even though the majority of what we work on was
originally developed prior to Kotlin going 1.0 and I had already laid out my
reasoning. It felt like excuses due to simply not wanting to learn and
maintain something new simply because they didn’t see any benefit, even though
I also explained the benefits in my original suggestion.

Thanks for your thoughts, though, I’ll take them into account.

------
bitL
OK, but where are the advantages? The page has just a different syntactic
sugar resembling Pascal/Scala; sine JVM nihil Kotlin anyway. Sometimes
Kotlin's "advantages" there have more boilerplate than Java...

~~~
deepsun
That's actually what I like about Kotlin the most -- it's just syntactic sugar
over Java, I wouldn't call it a new language.

E.g. if you want to parse a CSV or JSON, you would google "how to parse it in
Java", not "... in Kotlin". That's different, from e.g. Scala, where
everything should be Scala-way (of course you could use Java libs in Scala,
but it was always second-class I feel).

~~~
pkolaczk
Once you learn the Scala way of e.g. parsing JSON or defining any custom
parser or working with collections/optionals you don't want to look back. I
had to move back to coding in pure Java for a while after coding Scala many
years, and really it feels Java is making things far too overcomplicated in
many places.

~~~
bitL
Scala is overcomplicated. Java's goal was to get rid of C++ complexity, Scala
sneaked it back in.

~~~
pkolaczk
It is only because you are _familiar_ with Java. Scala is much different
language so it looks unfamiliar to you. But familiarity is not objective
simplicity. Java has many more gotchas and irregularities than Scala, and you
just got used to it, so you don't see it. Primitive types vs boxed types,
static state, default methods (poor man's traits), unsound array types, etc to
name a few.

Also it is funny to see how Kotlin or Swift are marketed as simple languages
when they managed to literally copy 90%+ of Scala features and make some
actually even more complex (eg nullability).

If you say "overcomplicated" it suggests you have a simpler solution for the
same problem in mind. So, what exactly would you simplify in Scala? Which
unnecessary features would you remove? It is easy to throw an "X is
overcomplicated" statement but much harder to point to concrete things that
could be done differently. Sure, some stuff could be easily removed, but not
without making the language less expressive.

~~~
bitL
Look, Java was born when C++/CORBA dominated investment banking and everybody
was having headaches with those. Java was like "manna from heaven" that made
everything orders of magnitude simpler. It still didn't get everything right,
like too much boilerplate, but simplicity of approach was there. Then Scala
arrived, and obfuscated everything. It didn't retain simplicity of either Java
or Haskell, instead went full-blown C++ "many styles" way. As a consequence,
either all of your team is on the same level in the same areas in Scala, or
you are going to have "fun" in production. In Java the syntax was quite
trivial, in Scala one has to fight with DSLs of different frameworks and
unintended consequences of various higher-order structures originally designed
to be "simple".

------
svnpenn
I learned that Kotlin has a native compiler:

[https://github.com/JetBrains/kotlin-
native](https://github.com/JetBrains/kotlin-native)

does this mean end user can run without JRE? Does Java proper have something
similar?

~~~
ajross
Java had a native gcc front end way back in the 90's. No one used it and they
eventually dropped it. This isn't really a killer feature for the problem
areas targetted by Java developers.

Android ART is, effectively, a native compiler for a Java-targetted (but not
JVM) bytecode too.

~~~
vips7L
I think one of the main use cases of graal native will be for container's with
smaller memory footprint (where GO traditionally shines) or where startup time
needs to be fast.

------
aliakhtar
It pisses me off a bit to not see Scala mentioned anywhere. Scala has
everything Kotlin has, and a lot more.

~~~
wskinner
Which could be considered a reason to use Kotlin instead. Scala is a more
powerful footgun. You pay for the power in overengineered code, slow compile
times, and worse compatibility with other JVM languages.

~~~
pkolaczk
Scala compatibility with JVM is the same as Kotlin's. It is implemented the
same way in both languages - they compile to JVM bytecode and as long as you
keep away from non-Java features, interoperability is good both ways. If you
start using stuff not directly supported by Java like default arguments or
multiple inheritance of traits, then calling Scala/Kotlin code from Java is
similarly bad experience. Scala has also a few more non-Java features e.g.
macros or implicits, so I get how you could end up with this impression. Just
don't use these features of you need to call your code from Java.

As for compile times, Scala with Bloop is the fastest of JVM languages I ever
saw. We switched to compile Java with Bloop because it is orders of magnitude
faster than Maven/Gradle. Bloop works for Java and Scala, but not Kotlin. So
Kotlin, having really nothing comparable at the moment, is currently the
slowest to compile from these three languages.

~~~
izolate
Something doesn't add up. First you say (emphasis mine):

> Scala compatibility with JVM is the SAME as Kotlin's.

Then you follow up with:

> Scala has also a few more non-Java features

These are contradictory claims. OP had a very good point about Scala being a
more powerful footgun. Unfortunately, consciously avoiding features is not a
matter of "just", and rarely works out in practicality.

~~~
pkolaczk
No they aren't contradictory. What is the compatibility of a feature that even
doesn't exist in Kotlin? How can be the lack of way to call a Scala macro from
Java a disadvantage, when Kotlin doesn't allow you to call a macro from
neither Java nor Kotlin, because this feature doesn't exist? Scala is strictly
superior in this case.

And you need to avoid some features only in code that gets called _from_ Java,
not the whole codebase. Calling it this direction is very rare and not really
a problem. Most codebases call Java from Scala and this is easy and fully
supported.

~~~
AlphaSite
100 intercompatiblity is a feature.

~~~
pkolaczk
But Kotlin doesn't have 100% interoperability! There are features in Kotlin
which don't map nicely to Java features. For example you can't call methods
with default arguments from Java without resorting to unreadable hacks relying
on a way defaults are implemented (same is true for Scala).

------
jariel
I tried Kotlin for some time and went back to Java.

Kotlin is nice, and on some days preferrable, but the fact of the matter is,
it's really not that much more legible or succinct than Java in the long run.

Look at Androind BTE docs [1] - the K vs. J examples side by side, there
really isn't that much difference.

In the end, I feel K is just a 'different flavour' of Java, and often I feel
that the makers of K are just throwing a bunch of ideas together, without
necessarily having a philosophy.

Given a choice between a 'world of J or K' \- to me, it's kind of a toss up -
but in reality - J is the incumbent. You have to know J and deal with J at
every step, all sorts of libraries are in J etc. etc. - so in reality, the
offer of Kotlin is really not Kotlin, it's always Kotlin+Java - meaning two
languages and paradigms to support.

If this were 1996 and we had to pick between DVD and BlueRay, it would be a
difference decision, but in the end, it's not really 'either or', it's J or
J+K.

In the end, J is not that much more hard to write and the differences are
negligible except for some specific things ... so I've switch back to J and
don't miss K.

[1]
[https://developer.android.com/guide/topics/connectivity/blue...](https://developer.android.com/guide/topics/connectivity/bluetooth#kotlin)

------
ljackman
I wonder whether Project Loom will create a split in the Kotlin ecosystem
between coroutine-based concurrency and Loom lightweight thread-based
concurrency.

Java will have a similar problem with CompletableFuture and third-party
projects like Reactor used in Spring WebFlux.

However, Kotlin baking in language syntax for a competing concurrency model
will exacerbate the split.

With Java already having type inference, concise lambdas, and with upcoming
records that can already be faked in current versions via Lombok, the value
proposition of Kotlin seems questionable outside of Android with its held-back
version of Java.

Clojure is another story entirely, offering a very different and compelling
way of thinking about computing on the JVM. By contrast, my developing view is
that Kotlin is different enough to require learning something new yet not
different enough from modern vanilla java to offer substantial advantages.

------
eganjs
I think one feature of Kotlin that is underestimated is extension functions.
Combine them with autocompletion and you've got a great developer experience.
Finding the method you need no longer requires a Google, and optimisation pays
off massively in terms of productivity by tightening the development loop.

~~~
zaphirplane
Extension functions are dispatched statically which can be surprising if you
can’t tell what is an extension and what isn’t

------
afandian
I like Kotlin (as a half-way house in a Java codebase to something purer like
Scala) but I'm worried about being locked in in future, and that becoming a
liability in a codebase 20 years from now.

Does anyone have experience of emergency automatic conversion back to Java?

(Edit: Never used Kotlin but I like the look of it)

~~~
thu2111
There's no direct conversion back. IntelliJ has a decompiler that produces
reasonable-ish Java code based on the debug symbols, so you get things like
local variable names and obviously method/class names back, but, it's a
decompiler, so no code comments. And Kotlin constructs frequently require
synthetic Java variables to be created that were implicit in the Kotlin, so
you have to clean up the result quite a bit.

However note that Kotlin and Java code can co-exist very closely in the same
codebase. In the same way you can incrementally port a Java codebase to
Kotlin, so too can you incrementally port Kotlin to Java. There's just no
automatic tool for it like there is Java->Kotlin.

~~~
afandian
Thanks for that. I think I'd misread something then and thought that it could
work both ways.

------
echelon
All of this stuff will eventually wind up in Java, and when it does, Kotlin is
going to feel an awful lot like Coffeescript. The Kotlin proponents of today
are going to feel a bit silly.

I predict there's going to be a lot of effort wasted porting old Kotlin code
to Java 20 or some such.

Willing to place a longbet on it.

~~~
enitihas
But all of this stuff simply can't end up in Java, because of backwards
compatibility. For example, kotlin object references are non null by default.
That is not something Java can easily bolt on. I think there should be many
such features.

------
lenkite
Raw, multi-line strings are coming in JDK 13 thanks to
[https://openjdk.java.net/jeps/326](https://openjdk.java.net/jeps/326)

~~~
Polyisoprene
Java 13 was released 2 months ago.

~~~
lenkite
I am _so_ outdated. (Our company uses an internal licensed version of the JDK
and we don't have JDK 13 yet)

------
ragnese
So choosing Kotlin over Java boils down to some syntactical differences? Nah.
The syntax differences between Kotlin and Java are not even that huge. It's
not like choosing between Elixir and Erlang, or between JavaScript and
ReasonML.

The main differences between Kotlin and Java are:

* Kotlin forces null checks.

* Kotlin arrays are invariant.

* Kotlin does not have checked exceptions.

* Kotlin has first class functions.

* Kotlin sealed classes don't really have an analog in Java, AFAIK.

I don't find data classes to be a big deal. The best thing about them is you
get `copy()` for free.

------
chrisseaton
Why don’t the Java examples use var?

~~~
driver733
They will. I am in the process of updating Java code snippets to Java 11.

~~~
vips7L
Probably should do 13 since it's the current release.

~~~
driver733
Sure, but you have take into account that Android devs are limited to Java 6,
most enterprise devs (based on my experience) are still on Java 8 and some are
still on Java 5 or below.

~~~
vips7L
Yeah this is nonsense and isn't an argument against the language. Embedded
devs aren't allowed to use Rust, does that mean we shouldn't compare C++ 20 to
Rust? Does that mean Rust is a bad language? If these said devs are limited to
Java 6/7/8 does their company have the inertia to use a brand new programming
language (Kotlin) that their devs don't know? Does this mean Kotlin is bad
because they're not using it?

This is a bad argument.

~~~
driver733
My goal is to compare Kotlin with the current version of Java along with any
Java libs that are commonly used (such as Lombok). I have mentioned the fact
that some teams are still on older versions of Java just to highlight that not
every developer can access the features of the latest Java release.

~~~
vips7L
Unless it's Android, if they can't access the latest features of Java they
more than likely can't access the latest features of Kotlin either.

~~~
driver733
That's not always the case, since Kotlin can generate Java 6 compatible
bytecode.

------
dep_b
These examples don't show the true power of Kotlin, for example pattern
matching is super powerful and helps to put a much more solid and readable
logic in your applications.

Still a lot of Kotlin I see from my Android colleagues suffers from all the
CONSTANT_STRING_TYPED magic and onion architected* stuff either inherited from
the libraries and API's or ingrained into their programming habits.

* many layers, and every time you peel off another layer you feel more like crying

------
KorematsuFred
A lot of this could be misleading, a programming language can have excellent
syntax to do something small and yet might turn out to be a horrifying if you
are going through a complex system.

Having worked with Kotlin I do love the language though. There are some
features like extensions which I hate. But in general I love the syntax though
I do not find any significant advantage of using it over java.

------
AndrewBissell
Very nice catalog of comparisons. IMO it could also use a section on
"Generics," Kotlin's declaration-site variance is a nice improvement over Java
wildcards.

[https://kotlinlang.org/docs/reference/generics.html](https://kotlinlang.org/docs/reference/generics.html)

------
didibus
To those who've done a lot of Kotlin, does it actually alter your programs'
design and structure? Your approach to problem solving? Does it open new doors
in how you choose to think about and attack a problem? In a nutshell, do you
think your programs are better because you chose Kotlin over Java and why?

~~~
jillesvangurp
I've converted a lot of Java backend code to Kotlin. You usually start out
with the intellij converter. I tend to go class by class. That leaves you with
something that nearly compiles but not quite. After addressing that, you
typically end up with some needlessly nullable types, lots of mutable types,
some misguided generics and a few other java-isms that are easily fixed. So,
far you've not really changed the structure of the code, you're merely
improving it and making it more safe to use. I usually get the process above
over in a few minutes for a single class; it's not hard and I would argue the
resulting code is already massively better than what you started with.

After that, there are probably a few places where idiomatic use of Kotlin
library and extension functions can improve things. I tend to that as I
stumble on opportunities to do so. This stuff is great for getting rid of
boiler plate. E.g. Kotlin's internal DSL language features can replace a lot
of ugly builder pattern code. Also having constructors with default arguments
removes the need for having builders or having multiple constructors. Same for
functions.

Converting streams to sequences and restructuring statements with nested
returns to return the result of a complex expression helps to. Using when
instead of if makes things nicer. Etc. Lots of stuff to use.

My programs are definitely shorter in Kotlin and safer (e.g. nullability).
Shorter is correlated with lower maintenance cost in literature on software
engineering. Some things that Java is ok with are compile errors in Kotlin.
So, safer is better in my book as well.

------
melling
I like a succinct way to define immutable variables. That’s what I do by
default in Swift

    
    
       let str = “foo”
       let age = 10
    

Kotlin does this with val, which is great.

How do Scala and Kotlin compare?

Next time I’m back on the JVM, I’d like to one of these two, perhaps both if
they interoperate.

------
nurettin
Out of topic, talking about language defaults, I wish C++ defaulted to const
reference instead of value. True that it would lead to some pitfalls such as
having to explicitly copy values during initialization, but it would make
things much less verbose.

------
mike_kamau
Kotlin is like a virus. Once you use it in a non trivial project, it infects
you and takes over your body and mind. Every time I look at Java code in my
Android apps, a part of my body hurts. Luckily there exists a Java to Kotlin
converter.

~~~
jmkni
It reminds me of moving from VB.Net to C# years ago!

------
EsssM7QVMehFPAs
Kotline looses me at _val_ vs. _var_

So much focus on readability otherwise, what happened there?

~~~
jrempel
value vs variable. As someone that works on both Kotlin and Java daily, what
is issue? 95% of the time I'm using val.

~~~
Larrikin
They also look completely different in the IDE

~~~
dep_b
They should because it's very easy to miss when skimming over the code
otherwise.

------
fiatjaf
See also:
[https://rosetta.alhur.es/compare/Kotlin/Java/#](https://rosetta.alhur.es/compare/Kotlin/Java/#)

------
peter303
Kotlin is people impatient with the glacial evolution of Oracle Java.

------
volgar1x
Kotlin really shines when it comes to async programming. This is some code I
wrote using Vert.x with Kotlin extensions :

    
    
        router.get("/api/article/:id").coroutineHandler { ctx ->
            val news = newsRepository.get(ctx.pathParam("id")) // no need for await
                 ?: return ctx.respondText(404, "Not Found") // can still use basic code constructs
            ctx.respondJson(200, jsonObjectOf("news" to news)) // actually an extension method i wrote
        }

------
balladeer
Though I do find Java's String concatenation cleaner than Kotlin's (refer:
Strings II comparison/example, the 2nd last)

------
vmchale
The Null II example and the Elvis operator look like special cases of monadic
bind/functorial map.

------
zonidjan
This seems great.

For someone who already knows Kotlin.

------
aliakhtar
For fun, I'm going to rewrite all of the examples in Scala:

1) Main

def main() = println("Hello")

2) Variables:

val y = 1

3) Options (nulls are discouraged):

val name: Option[String] = None

4) Null 2:

//If bob is not null, get his age, or get a default age

val age = bob.map(_.age).getOrElse(0)

5) Elvis operator

Kotlin:

val result = nullableVariable?.someMethodCall() ?: fallbackIfNullMethodCall()

Scala:

val result = option.map(_.someCall()).getOrElse(defaultValue)

6) String interpolation in scala seems to be exactly the same as kotlin:

val name = "John"

val lastName = "Smith"

val text = "My name is: $name $lastName"

val otherText = "My name is: ${name.substring(2)}"

In addition, you can also have:

val longString = s"""

|This is line 1

|This is line 2, my name is $name

""".stripMargin

7) This shows the same multi-line strings as above, but its unclear if you can
have variables in multi-line strings like I showed above in Scala

8) Ternary operator:

val text = if (x > 5) "x > 5" else "x <= 5"

Some bonus stuff which scala has:

9) Case classes:

case class Person(name: String, age: Int)

10) Pattern matching

person match {

    
    
      case Person("bob", 13) =>
    
          println("Matched bob with age 13")
    
      case Person("sally", _) =>
    
         println("Matched sally, age unknown")
    
      case Person(name,age) =>
    
        println(s"Matched unknown person with name $name and age $age")
    
       case x:_>
    
          println(s"Matched unknown item: $x")

}

10) Equality which actually makes sense, i.e

val foo = "foo"

val bar = "foo"

foo == bar //true in scala, no need to foo.equals(bar)

val bob = Person("bob", 13)

val other = Person("bob", 13)

bob == other //true, based on values

val list = Seq(bob)

list.contains(other) //true, based on values

11) .par collections / way better higher order functions

val list = Seq(string1, string2,...)

//Do a parallelized search on list to find all strings <= 3 chars in length:

val shortStrings = list.par.filter(_.length <= 3).seq

12) Try:

val riskyOp = Try( doSomethingRisky() )

riskyOp match {

    
    
       case Success(result) =>
    
            println(s"Op succeeded with result $result")
    
       case Failure(e) =>
    
            e.printStackTrace 

}

Disclaimer: I wrote all these in the HN textbox, please excuse any typos

~~~
gentaro_
Could you please also provide Scala versions for the other code snippets on
that site? Just what you can come up with from the top of your head?

I'm genuinely interested, having spent the last few years with Haskell and
having recently rediscovered and being incredibly awed by the JVM and its
ecosystem, and pondering on whether I should refresh what I'd known of Java or
just outright embrace Scala.

~~~
aliakhtar
You should definitely go for Scala if you're coming from Erlang. You'll find
it much more Erlang-like.

I don't have the time to convert their whole site right now, sorry, but you'll
find the same pattern holds - Scala does everything more elegantly and
concisely. Feel free to look up a Scala tutorial.

~~~
gentaro_
Great, thanks! Do you think Martin's textbook on Scala is recent enough
relative to the present state of Scala as a language? I also see Scala 3.0 is
in talks, nice.

~~~
aliakhtar
I found that to be a bit dry personally, I personally just looked up Scala
tutorials online and followed them

------
dionian
what i want to see is kotlin vs scala

------
unnouinceput
I love programming languages that are case sensitive. So easy for each
programmer to have their own programming style on naming variables and then
errors galore, which in the end will result in hiring an outside senior to
clean-up the mess - that's me of course, and all for heavy money.

Somebody please invent another case sensitive programming language, we don't
have enough of them already.

~~~
dboreham
Aren't they all case sensitive since FORTRAN and BASIC?

~~~
klodolph
Pascal, R, Lisp, Ada, SQL are case-insensitive.

~~~
andrewbinstock
And COBOL, don't forget COBOL! ;-)

