I've only used Kotlin on Android, but from what I remember co-routines are not necessary to use. If you don't like them, then don't use them.
Kotlin has a number of advantages over Java. The biggest of which is built-in optional typing. It's also really nice that everything is expression instead of a statement. Library functions like `let` also make code a little nicer to write. And stuff like data classes and better property initialization are icing on the cake. In my opinion, you can write Kotlin exactly as you would Java, but the development experience is much more polished.
Typing is not optional, everything in Kotlin is typed. What the language has is type inference. The following lines have the exactly same types:
val teens = people.filter { it.age < 20 }.map { it.name }
val teens: List<String> = people.filter { p: Person -> p.age <= 20 }.map { p: Person -> p.name } final var teens = people.stream().filter(p -> p.age < 20).map(People::name).toList()The extra sugar on top is super nice too - listOf, mapOf, x to y, apply… I think it just makes code that much cleaner. None of these are make or breaks but together they work amazing. A lot of what I work on professionally is still on Java 8 or 11 so I don’t get any of the cool features like record types.
Most of the OSS I do is Kotlin bedsheets I just enjoy writing Kotlin. I don’t feel that way with the older versions of Java (I’m starting to with the newer ones).
Java spring does the same thing: if you use an unboxed type (int instead of Integer) and the client passes in null, the handler will never be invoked.
I've found myself with this a lot on "progress" data classes where I will be building up a set of data over several expensive calls. I /could/ make a new type per current state of that, such that I never have nulls. I /could/ make it so that every field is Optional. Or, I could work on a convention that fields are filled out in order, and after the first null, nothing is available. In many years, this has not been where null pointers hit me.
Theoretically everything worked. However, the end result is (1) the customer didn't get their renewal notice and (2) we got a validation error instead of (maybe) a NPE somewhere. So what exactly are we accomplishing here is my broader point.
In a case where the client expects an immediate response (http GET) getting “400 validation error: foo is not allowed to be null” is a lot more meaningful than “500 Null pointer”.
In general I try not to model invalid states - less mental overhead (no one has to tell you xyz can’t be null it just cannot be null).
Ofc this is a matter of opinion and the lines get blurred as soon ad you move stuff to runtime.
While Javas checked exceptions had a lot of problems, at least there was a way to declare the output (errors are ouput) of a function on a type system level.
With Kotlin, that's just gone. You can fiddle with Result type (or make your own), but you lose a lot of the ease of "bubbling up" errors.
How do you handle errors? (I wished Kotlin had error handling like Rust, which is the best that exists, imho)
I have no experience with Kotlin yet, but I recently did some Java after years of js/ts, and was nearly driven mad by constantly having to convert different kinds of collection. String[], Array, List, Iterable, Stream... and every library expects or returns something else, so you're constantly converting these things.
Any of them would have been perfect if only it had been supported by everything, but because of Java's long history of constantly inventing newer and better ways of doing things, libraries written at different times support different kinds of collections and you constantly have to convert them.
In the different collections, you see a history of 20 years of developer experience improvements coupled with an almost religious emphasis on backwards compatibility in the language and standard library.
In every (long term) JS/TS project I worked on, about 20% - 50% of the development time went into upgrading libraries and keeping everything running on the current node version. It was maddening. Stuff like the different types of collections are a very small price to pay, IMHO, if you can be sure that your current Java project will with very high probability also run on a current JVM 10 years from now.
That's actually why I prefer List, because a List is an interface and can be an ArrayList or another type of List and I don't care about the implementation, as long as it's a List. But Array is an array that's not a List, and Iterable is also an interface, and I think a List is also an Iterable, but I'm not sure, and I suspect not every Iterable is a List. And then there's Stream which should have been a set of convenient functions that are part of List or Iterable right from the start, but they're not. And what the hell is a Spliterator and why do I need one to turn an Iterator into a Stream?
I understand that there are reasons for this, and I totally agree that the js/ts dependency situation is far from ideal, but it's still maddening to have so many different collection types, when js/ts just has an array that's not even an actual array, but it still works fine, and all the new stuff just gets added on top of it.
One of these days someone should invent a new programming language that finally gets all of this right once and for all, but I bet people will find ways to improve it again.
It "works fine" for basic cases but it doesn't give you anything like the same capabilities. JS/TS have no easy equivalent of array or stream, anything you could write in js/ts you could write in Java by only using ArrayList. Java's collections library is big and complex but almost everything that's in there is there because it has a use case, and while it's showing its age now it was well designed for its time.
> One of these days someone should invent a new programming language that finally gets all of this right once and for all, but I bet people will find ways to improve it again.
Your best hope is a language with Haskell-style typeclasses where you can not only add new implementations of existing interfaces, but also retrofit new interfaces onto existing implementations. No library is going to be perfect from day 1, and a big part of the reason why Java Stream is awkward is that it had to be retrofitted into the existing collection library.
Stream usually is not used other than for call chains. Like list.stream().map(...).toList();
I write Java for many years and I can't really say that this was source of pain for me. I agree that streams could be implemented with better ergonomics, but Java designers wanted to provide us means to use parallel computations with one extra word, so here we are. I've yet to find a place where I'd want to use that.
I used collection classes in Java 1.4 and I'm using them in Java 19 and I don't think that anything changed in that regard. Collections are the same.
Yes, but every library I use requires or returns a different one.
> list.stream().map(...).toList()
But why not list.map(...)?
I have had some internal teams try to use Iterable or arrays, thinking they needed to be optimized. Almost without fail, those are from teams that stall out and never actually finished what they were doing.
I have seen case studies of giants that actually needed to optimize down to arrays or buffers, but this is often not the case. I'd imagine unless you are trading or gaming, you can get more than enough mileage out of List. (Specifically ArrayList. LinkedList is usually a sign of premature optimization without having actually benchmarked what was running.)
One my pet peeves, shit like this sucks :
var f = MyStupidMethod();
val foo = new MyReallyLongUglyFactoryClass()
instead of: MyReallyLongUglyFactoryClass foo = new MyReallyLongUglyFactoryClass()
And you never _have_ to use type inference. If you have a method where the return type isn't as obvious, you can always annotate it explicitly: val foo: Int = doSomeThing()
Do people exercise judgement about when to make the type explicit? Eh, depends on the team. But if you combine type inference with established conventions in a particular codebase (e.g. I/O calls always return IO[Foo]), you will rarely be left wondering what the type of something is.> var conn = openDatabaseConnection();
Are you actually confused about what conn represents? Does it matter what the exact type is, if you already know what it is and what you can do with it?
this line has zero readability
you're not writing code for compilers, you're writing code for people
Fundamentally, this is a story of technology getting better (type inference in compilers) so humans can do less work. We're not pushing the work to some other human place. We're not losing anything in safety, and we're gaining in readability, boilerplate and expressiveness. Its progress!
i agree, thats why i don't want to clutter my code with annotations designed for the compiler, not humans. Type inference is a _good_ thing for readability.
Since the actual size of the code base isn't an issue in the modern world, I personally like that the Kotlin ecosystem discourages the use of esoteric names and non obvious abbreviations. Once you write and read enough of it you stop making poor choices.
> var f = MyStupidMethod();
Yeh, but so does:
List<MyWeirdoFooClass> myWeirdoFoos = new ArrayList<MyWeirdoFooClass>();
Sometimes it's clear what it is. Sometimes you don't really care. Sometimes you do. You can still make it explicit when you need it to be explicit.In theory this is possible to approach with annotations but I found it hard to keep up in a large codebase.
I think the point is to be calling them asynchronously. Unfortunately async programming is kind of contagious and difficult to shoehorn into sync stuff but if it’s written asynchronously there’s usually a reason.
Records ergonomics is terrible if you want to replace data classes with records, even if immutable is OK. You need to write builders. You can't really write code like
new Person(id, null, null, null, lastName, firstName, null, null, null, null, null, null, null, age);
Withers can help with that, but they're not even in any kind of experimental shape right now, so we have many years to wait for it.Right now records are only fine for very simple use-cases like Point(x, y). Or if you want to write or generate builders. But at this time you don't really save anything, if you can generate a builder, you can generate a class as well.
If you have data class with more than 5 fields then you have it wrong. Builders are like lombok and like field injection: hide poor class design.
If using a class hurts, it is badly designed and should hurt until it is refactored/split up into consumable parts.
I use records extensively, but those are in most cases converted classes which were small and immutable. JPA being one of the exceptions (a stuck in the past spec)
There are very few cases where you need to work simultaneously on that many columns.
However as any async/await implementation it will obviously still have challenges. The "colored" world of functions means users need to know the differences between suspend functions and other functions, and using something wrong can lead to performance issues.
One thing to note is that with the upcoming of virtual threads (Project Loom) in Java itself, the need for using coroutines might become much smaller. You might just end up using them for UI work, and everything else could use virtual threads. That could simplify a lot of things.
And since it is API compatible with things that are already supported by co-routines, pretty much all you need to do is change your custom co-routine contexts to be backed by virtual threads rather than actual threads. This should just work even without explicit support for this in the co-routines library (it's just another thread pool). But they obviously will add explicit Loom support as well as it makes sense to make co-routines be virtual threads pretty much always.
When that ships, all current kotlin code that uses co-routines will be using virtual thread on a Loom capable jvm. It already has structured concurrency and all the rest so all of that will continue to work. And some of the blocking Java stuff that you currently need thread backed co-routine contexts for, will stop being blocking so you can stop doing that. But it will still work of course.
If you already use Kotlin coroutines - fine to continue to use them. But I imagine for a new project you might want to opt to build on virtual threads instead of coroutines.
Use a proper asynchronous framework and then the only thing you need to worry about is avoiding calling synchronous code on your main thread (i.e. dispatch it to some thread pool backed co-routine context). Not that hard. And you can get rid of a lot of that stuff by gradually switching to non blocking versions of whatever you are using.
If you are exposing class properties without accessors in Java, that's not necessarily a great thing. Especially if your state is non final (i.e. mutable). In Kotlin, you'd use vals (or vars if you really have to) and by default they just behave like they have getters/setters. But you don't have to spell it out. And you can override the getters and setters. Just like you would in Java. It's just the distinction is not there. It's basically a less hacky Lombok.
The weirdly positioned text that your IDE adds are called hints and you can turn them on or off as you please. They are there to help you. Type inference is a nice thing: it means you can read the hints without having to spell out what is what. Java has type inference too but it's a bit more limited and more verbose. There is no uncertainty about what the type of anything is in either language: exactly what you specified (but just once in Kotlin's case).
In general Kotlin is more concise, checkout these examples:
https://stackoverflow.com/questions/34642254/what-java-8-str...
With streams and the var keyword, Java is also not that much more verbose anymore than Kotlin and the code completion, error detection and refactoring capabilities are much better in Java. In Java I can also be sure that if I directly access a property on a class, there will be no side effects or expensive operation while if I use a getter, there might (and I dont have to write them either due to code generation or Lombok). So the parts where Java is still more verbose actually add clarity (and again, due to the IDE, you rarely have to type any of it): I dont really get why I would leave out the explicit types in the source code, only to be added again as non-editable, weirdly positioned text by the IDE (which is not there if just wanna have a quick look at the code on GitHub).