123 points · by andreygrehov · 9y ago · 161 comments
Learn the collections library. https://kotlinlang.org/docs/reference/collections.html All loops can be written in terms of them. Also because of inlining they have have the same runtime costs as hand written for loops.
"Smart cast to ‘Int’ is impossible, because ‘value’ is a mutable property that could have been changed by this time"
Smart casts only work on immutable values because of concurrency. If the variable hast to be mutable use ?.let { ... } instead of smart casts.
What's wrong with two exclamation points? If you're using it you are probably doing something wrong anyway.
When getting a type from Java that hasn't been annotated as @NonNull or @Nullable it is regarded a platform type. This means it's programmers responsibility to check if it can be null. Same as in Java or any other language that doesn't have nullable types.
Assignment is not an expression. We've written 20K of production Kotlin code without this ever being a useful convention. Assignment being an expresssion is layover from the C family of languages. If you really want C's syntax and semantics, go write C.
The ?: operator is great when chaining a bunch of operations all of which could return a null which we want to convert to a default. Here is an example: claimData?.claimTimeMinutes?.toLong() ?: 5L
Generics in Kotlin have the same issues as Java because of type erasure. It does offer a few improvements with the use of reified type variables.
Lastly, if you want to have descriptive structures use data classes.
This guy just wants to program in C. If it's not C it's crap according to the article.
Out of curiosity, what is the idiomatic way of writing an input loop? The C/Java way would be something like
int bytesRead = 0;
while ((bytesRead = in.read(buf)) != -1) { // ...
> The ?: operator is great when chaining a bunch of operations all of which could return a null which we want to convert to a default. Here is an example: claimData?.claimTimeMinutes?.toLong() ?: 5LI think the author is referring to the ternary operator, not the elvis operator.
in.buffered.readText()
The Kotlin stdlib has a rich set of extension methods for reading in whole files of various common formats at once. readText() reads it all into memory at once. readLines() reads it into a list of Lines. forEachLine{} runs a closure on each line. useLines reads it into a sequence (a lazily-evaluated collection) and then passes that into a closure. buffered converts it to a BufferedReader, basically wrapping it in your buffering loop. inputStream converts it to an InputStream, reader to a Reader, and most common Java protocol libraries take one of those two, so if you need something more complicated you just pass that in.I've yet to write an input loop in Kotlin.
for length, bytesRead in input.bytes() { //...
Edit: quick google search, the actual syntax is file.forEachBlock { bytes, size -> //...Python doesn't treat assignment as an expression. E.g. I can't do:
if a = 1:
pass
or def c():
return a = 1
or: a = lambda c: c.x = 1
But I can still do: a = b = c = 2
to set multiple variables at the same time. if not 10 < x < 20:
raise ValueError("Out of range.")
Not every language allow this. c = 2
b = c
a = ba=b=c=2. They're all equal, all variables here equal 2.
My team has a significant investment in the JVM. I despise working in Java because of how heavy it is to write. I like Scala, but the team I'm on finds it too complicated. Clojure is out because nobody on the team wants to write lisp. And Groovy doesn't have types. We looked at Ceylon, too, but at the time we hit a lot of compiler issues (if I remember correctly).
So where does that leave us? There are likely other languages we could choose that target the JVM, but the pragmatist in me says I don't want to stray too far off the beaten path for this.
Is Kotlin perfect? No. But is it a better developer experience than Java? Oh hell yes.
Only if your site has upgraded to version 2.x of Apache Groovy, which many sites haven't. Even then, converting everything to @CompileStatic at once only works wholesale for tiny codebases. You'll face a lot of debugging for anything larger -- it's more like "throw" a @CompileStatic onto one class at a time, and test after each. You'll hit the wall soon enough. Consider why Groovy itself is still written in Java, not in statically compiled Groovy, and there's certainly no mention of converting its codebase anytime soon in the latest roadmap posted on their developers mailing list a day ago.
And of course Groovy, unlike Kotlin, only triggers IntelliJ's (and Android Studio's) code completion perhaps 80% of the time. Kotlin was created by the same people who built IntelliJ and for the explicit purpose of working properly with it 100% of the time.
You are not in sole control of your code base. You share it with your colleagues who are on different skill levels. You are drawn into community gathered around the language and you need to use, debug, and sometimes contribute to other people's code. Just fencing off some common language features isn't going to cut it. It's better to select tools that are well suited to problem at hand, at right level of abstraction and of manageable complexity to your team. Even if that means less features and more ground work.
If you introduce exceptions in C++, everyone working on any line of the codebase needs to understand exception-safety. If you introduce RAII you have to enforce it on every constructor, and since constructors can fail you have to introduce exceptions. If you introduce templates you have to use RAII for all your types in case they're used in a template.
In Scala if you use a higher-kinded type it works exactly as you'd expect (indeed I'd argue that the absence of higher-kinded types is equally confusing - why can't I use List as a type parameter in Kotlin?) - a method or type that uses HKT acts like any other method or type. If you have a function whose implementation uses a pattern match it might make it confusing to read that function, but to any caller from outside that function still conforms to its signature and still makes sense. If your colleague writes a Profunctor instance for one of their types and litters your code with ^>> calls that's probably annoying (and should probably fail code review), but ultimately it's just a plain old function call that you can click through to in your IDE and see what it's doing and whether it makes sense.
In my experience with quite a few Scala project with mixed teams it's not a problem though.
You just maintain some shared culture of "don't do X if not absolutely necessary". You need that for any language. In this case it's: don't do typelevel tricks if you can help it. And it turns out that 99.9 % of non-framework code doesn't need it. And the large majority of devs are fine with writing clear code.
Then there are some smart devs that are at a stage of personal development where they are intrigued with typelevel tricks. I've only had one colleague who didn't wasn't open to the "hey, that's not really necessary there. Let's not add complexity if we can help it" type of code review comment.
To each his own. But for the teams I've worked with Scala was the typed-FP-on-the-JVM lets-get-shit-done language.
Again, using Scala's advanced features isn't akin to something like using raw pointers in C++. I find Scala's collection library a good example of that - programmers of all levels can use Scala collections without understanding all the type-level tech they're implemented with.
To provide a bit more depth, a large number of the developers I work with (folks I respect) don't _want_ the kitchen sink. They see it as dangerous. Even if _they_ can handle it, they know that there are a lot of people who can't. Sure, you can limit the features you use via convention, but that is shifting a tech problem to being a people problem -- you usually want to go the other direction.
You can "yeah, but..." all you want, but it's a valid, reasonable opinion. It's subjective, but that's just the way of it.
I tried everything. I made some nice Java interfaces so they could write plugins; exposed all the data they needed, wrote a bunch of documentation, had a learning session. No one contributed a damn thing.
They started firing people after I had already left for Australia and was working remotely. They kept me on while secretly having a former Amazon person rewrite my entire service in Java. Good thing I explicitly asked for the whole thing to be kept GPL prior to the contract.
Last year I got hired into a team that does the majority of their work in Scala. It's been a great experience.
You mean "old", not "mature". Scala is old and still pretty immature for its age
The Kotlin tooling and IDE support is certainly already way ahead of Scala's after just a year in existence in robustness and functionalities. And I'd rank the two compilers at about the same level in terms of maturity (Kotlin's is much faster than Scala's though).
In particular, nullable types seem like a good idea (I thought so as well) but in practice are a real PITA. That's most acute when defining fields, where non-nullable fields have to be initialized directly.
JetBrains themselves realized it was painful, and so we have `lateinit` to define mutable non-nullable fields that can be initialized later. But sometimes it really is nice to be able to check if a field has already been initialized, which you can't do here.
I must now have spent an order of magnitude time dealing with the initialization of non-nullable fields than I ever did tracking null pointer exceptions.
That being said, Kotlin is still a net improvement over coding in Java. In fact, if you're going for a large codebases, I think it's one of the most tractable languages out there (C# is a strong contender as well).
I'm curious, where have you found the need for lateinit? Forcing initialization of non-nullable types has always seemed like a great idea to me, and learning to deal with it in Kotlin has made picking up Rust a lot easier.
lateinit is a crutch to get things working, not something you want to use long-term.
It's useful as soon as a field is managed by a container, which means it will most likely not be initialized at construction time of the object.
Examples of containers: Android, JavaEE, web servlet containers, DI frameworks, etc...
So basically, they are pretty much ubiquitous.
Most of which support constructor injection.
If you need a run-time check to figure out whether a supposedly non-nullable field has been initialized, that sounds like a code smell to me.
I see the fact that something can only be initialized late as an internal matter of a library/module/part of project/etc. that should never leak outside of it (i.e. the outside world should never have to deal with potentially uninitialized objects - if it has to, then the field is not really non-nullable).
If you are writing a library I think you should be able to use reflection to figure out if it has actually been initialized, or worst case scenario just catch the exception that is thrown if it isn't initialized.
Once the initialization step is complete, the field will never be null and no checking will be required ever again. But in the current state of affairs, you just have to make it nullable and sprinkle the `!!` operator all over your code.
Why are nullable types a pain in the ass? If I recall correctly, isn't a nullable something you have to opt into? Basically you can't get null on accident, but you can opt into it when null makes sense?
In particular, to his:
> Where does this absolutely crazy confidence of a compiler that each character of my program is an element of multithread concurrency come from?
I'd reply: why would the compiler have this absolutely crazy confidence that a particular character of your program isn't an element of a multithread concurrency? Why do you want your compiler to make assumptions about your code if it's not able to enforce them?
I don't know what's the right way to write what he means in Kotlin but in Rust it'd be something like:
match (value) {
Some(v) => v,
None => 0
}
Or alternatively: value.unwrap_or(0)
Which are both safe and, in my opinion, clearer than the proposed code in TFA. I would assume that Kotlin has a similar syntax for that use case?That being said I can imagine that having to interface with Java (which doesn't share the same "mindset") might be frustrating. It helps when all the language and its libraries are designed from the ground up around a certain paradigm.
But after spending some time in Rust and Swift, I learnt a whole new way of thinking about it. The killer combination is:
no null + immutable
I've taken this to javascript, and it is so much better. Just don't accept null values anywhere in the model code, and suddenly writing view code is super easy.
No more endless if-cases or ternary to deal with nulls.
when (value) {
1 -> ...,
2 -> ...,
null -> ...
}
The compilers doesn't let you forget to check for null.
It's smart enough to correctly evaluate and cast nested expression.
when (value) {
is null -> "nothing to see"
is Number -> "a Number: ${value + 1}"
is String -> when {
it.isBlank() -> "Blank String"
null -> /* compiler error, you already checked for null */
else -> it.trim()
}
}
Or val x = value ?: 5 /* use 5 if value is null)
val x = value?.some?.nullable?.chain ?: 5 /* use 5 if the chain can't be called */
Or val x = value?.let { /* work on non-null value */ } ?: alternativeI have not played much with Kotlin, but I feel like Scala deals with a lot of the issues he brings up already (although it has a ton of issues itself; some stemming from it being so tied to the underlying Java Runtime and others from bad design decisions).
Everyone else seems to be treating it like it's serious though. Maybe I'm just too infused with the joy of Rust, Haskell and other such languages to think anything slightly hysterical-sounding about the utility of non-nullable types and the possibility of mutation by other threads can possibly be anything other than parody.
First I though the article was being ironic, I end up understanding by thinking it is a completely a joke, not half a joke. Otherwise I do not understand:
- why the author compares '?' with '?:' as they are completely different things
- complains about automatic casting of class variables without understanding that the languages have threads ( "thread intersections occur on a very small size of the source code, but due to compiler’s repressive care about this feature" -> it is much better to crash your program randomly in production than a compiler error, ouh yeah!)
- complains kotlin has a useless for that only saves some lines of code (like few lines of codes repeated for every for you write in the code, which it is a lot of code)
- complains about the alias without understanding generics
- complains about poor generics without understanding generics
- etc
100% I wont hire him as a engineer
val myMap = mapOf(
"A" to 10,
"B" to 20
)
etc.Also, regarding that final sentence about matrices, that sounds like a perfect use case for type aliases.
> Why we don't call it "Void": because the word "void" means "nothing", and there's another type, Nothing, that means just "no value at all", i.e. the computation did not complete normally (looped forever or threw an exception). We could not afford the clash of meanings.
And then he doubles down on it in the comments:
> "Unit" just stands for "something that has only one value", it's a traditional name, comes from functional languages. I agree that this name is not very intuitive, but we failed to invent a better name.
He managed to convince me that Kotlin's highest priority was pointless academic nitpicking, and that's not what I'm looking for in a language. What I wanted was a solid JVM language that avoids all the unnecessary boilerplate of Java without diving headfirst into a morass of functional programming like Scala. I want something that's 100% practicality and straightforwardness, not something that thinks trying to emulate higher math is something to aspire to. Well, I guess there's still Jython, even if it is stuck on an ancient version of Python... (edit: oh, and Groovy... forgot about it because most people just use it for Gradle scripting)
[0] https://stackoverflow.com/questions/22654932/what-is-the-pur...
You can use Kotlin for Gradle scripting as well since Gradle 3.0 released about 6 months ago. Given that Gradleware also said they're switching their preferred language for Gradle addons to Kotlin from that version onwards, I'm guessing the same will happen for build scripts some day.
For:
Not sure what he's upset about, but there are many options in the standard library. I almost never use the language construct for it, and I'm very happy with it.
Nullable:
I never expected nullable to completely save me from all issues. It has the same function as the @Nullable and @NotNull annotations (and all the other variants). It gives you a simpler way to reason about nullability, and forces you to respond to it; you can't just ignore it.
Smart cast on mutable
I get that this sucks, but they can't show it to happen. Yes, the chances are small, but there could be concurrency issues. They have to account for that, and can't tell if your code is multi threaded or not.
Most of the time his issue can be solved with scoping, using ?.let or ?.apply
Java Nullability
What do you want from them? They have no ability whatsoever to control this. Either get annotations in the Java code if you can modify it (which is a good idea anyways), or wrap it and provide nullability information.
Assignment is not an expression
He got it. It's too protect against if(v=v). I know he makes a joke about automatic type casting, but if you're not assigning the result to anything, the logic in the if will still fail.
Elvis operator
I assume they removed Javas ternary operator to not get confused with the Elvis operator. ¯\_(ツ)_/¯ I kind of agree with him here unless I'm missing something
Automatic type casting
Frustrating, but safe
Type alias
I'm fine with it for simple cases, didn't want to parse his problem.
Generics
I hear his gripe, but at the end of the day Kotlin generics are Java generics. If there are some potential bugs in the compiler, report them and move on.
Structure syntax
I assume he means list and map literals. I agree it would be nice. Not sure why they didn't include it.
What I want is consistency. In Scala optional is always safe and null is never safe, and that's true whether you're calling a Scala method or a Java method (even the most perverse Java libraries don't declare themselves as returning Optional<String> and then return null). In Kotlin null is safe some of the time and not safe other times, e.g. if you're passing it to a method it might be fine or might not.
For example, in my own pure-Kotlin code, "val id: String" is a non-nullable type "String"; the compiler will guarantee that it is never null. "val url: URL?" is a nullable type "URL?"; the compiler checks for null, and I need to use ? or !! or a smart-cast to access it. HttpServletRequest.pathInfo is a platform type "String!", is marked as such in autocomplete, and could be either null or non-null based on the API; it's up to me to use it appropriately.
The difference between platform types and nullable types is that platform types can be silently coerced to non-null types, even though they may be null. This was an ergonomic decision; you use so many Java APIs in Kotlin that the language would be nearly unusable afterwards (kinda like how Scala, rather than being a "better Java", has developed its own ecosystem of idiomatic Scala code). It's a potential safety hole, but it's clearly documented; think of it like getting memory management right in a C FFI.
Well yeah. But Kotlin advocates say you're supposed to use those extensively.
> think of it like getting memory management right in a C FFI.
Yeah, that's pretty terrifying. I would never want to use a language that expected me to make extensive use of a C FFI. It was bad enough when I used Python, and that involved a lot less C than Kotlin does Java.
val x: Option[Int] = null someMethod(null)
might be perfectly legitimate or might not, but you can't tell without knowing the details of someMethod (whether it's a Java method or not).EDIT: should mention I don't know Kotlin so maybe there's something obvious I'm missing...
collection.forEach { variable ->
....
}Clojure works pretty well with Java, but is so different, you'll rarely get things mixed up between the two.
Just a guess, since I'm not the original commenter.
Kotlin is supposed to be less verbose but variable declarations and function signatures can get annoyingly long.
//java
String x;
//kotlin
var x : String?
Also, the whole fad of all new languages putting the type after the name doesn't make sense to me.Where are the ints?
Object objectThing;
Object someOtherObjectThing;
int thing;
int someOtherThing;
String stringThing;
String someOtherStringThing;
Much harder to find the ints in a long list of Kotlin fields: var objectThing:Any?
var someOtherObjectThing:Any?
var thing:Int?
var someOtherThing:Int?
var stringThing:String?
var someOtherStringThing:String?In Java Android code we normally group the fields by type to make them easier to find. But maybe we need a different convention for Kotlin.
Usually the name of something is more important than the type. In dynamically typed languages, the name is all you get, and it's enough for a lot of programmers to be perfectly productive.
// Java
String x = new String()
// Kotlin
val x = String()I disagree with the idea that the Ints are hard to find in their post. That's just not the hard part of reading code, though it's a good example of a pointless micro-comment-benchmark.
I probably misremembered quite a bit, but...
var value : Int? = null
fun F() : Int {
if ( value != null ) return 0
return value // error
}
Tracing value types through a function is a solved problem. Look at TypeScript: Almost the exact function above will work flawlessly. [1]Sure something in a JVM could be changed by another thread. But that would really be a bug no matter how you slice it. Doing type analysis like this seems like a minimal requirement for a modern language.
[1] http://imgur.com/nxdN9vc -- you can see that TypeScript can identify the remaining type. It works for optional null as well when strictNullChecks is enabled.
Let's change it to
var value : Int? = null
fun F() : Int {
if ( value == null ) return 0
return value // error
}
Now the compiler still complains, with a different error:"Smartcast to Int is impossible because value is a mutable property that could have been changed by this time". Right you are.
val value : Int? = null
fun F() : Int {
if ( value == null ) return 0
return value
}
This version compiles fine because `value` is a constant (though I think the compiler should've complained about dead code. You can never reach `return value`.) fun F(value : Int? ) : Int {
if ( value == null ) return 0
return value
}
This version also works fine.> "Smartcast to Int is impossible because value is a mutable property that could have been changed by this time". Right you are.
I disagree. It cannot have been changed by that time, not unless it was changed in another thread, and it would be really, really nice for a language to have built-in threading intelligence to prevent that from being necessary to check. That's what I'm saying. TypeScript is single-threaded, so it can be certain that another thread hasn't changed it. Go is multithreaded, but except for genuine globals (which need to be protected by a mutex, but shouldn't be used for just about anything) you're piping information from one state to another, which again doesn't have a synchronization problem.
If you have to manually mark a variable as "safe" every time you use it, you're just going to need to do that constantly for lots of variables. And you still are stuck getting the thread safety right: The above code isn't safe if something from another thread can change value. Which I guess is the point of the exclamation points, but ... somehow I prefer the Rust approach of "Mark this block of code as unsafe." Not that I've used either language.
The fact that it works correctly as a parameter, though -- that does hit the 80% case, at least.
That's the thing, it's not "80% of the cases". It actually hits just about all of them. For this whole situation to be a problem, rather than the compiler preventing bugs, you need all of the following:
— You need a `var`, rather than a `val` (constant).
— The `var` needs to be nullable.
— The var is either a module global, or a class field.
— Your code doesn't touch anything multithreaded.
This includes not using NIO, or having any callbacks at
all to libraries that might use threading internally.
If any of those requirements is missing, the compilation error is either legitimate, or gone. In my experience, eliminating the multithreaded part eliminates all the reasonable use cases for Kotlin-as-a-Java-replacement: Android, web development, desktop applications.Not all languages need to be good at everything. For my purposes, I welcome a language that makes working in heavily-multithreaded environments a bit easier, and I won't begrudge languages targeting other people's use cases either.
"I believe you intended to use `val` in your second example...". Fixed the example now.
Sure, i think that(type inference/flow typing) is solved in kotlin too. Sorry, i don't get the issue here. The last return value is throwing a compile time error because it breaks the function contract, which expects a non null value.
There are plenty of ways to do it. The most popular is probably to capture the Java nullability at the border when Java values enter Kotlin code. From that point on, your code is null correct and will never give you an NPE.
> The Smart cast to ‘Int’ is impossible, because ‘value’ is a mutable property that could have been changed by this time error is driving me nuts. I want to kill someone or break something.
Yeah, lash at the compiler for pointing out your code is incorrect, right? Easy solution: use a `val` (which should be your default anyway). Another solution, although less easy: write better code.
And if I max the screen... I still can't see all of the width of the code samples.
It's not so bad in landscape, however.
The title should be "Kotlin Sucks" or "Why I think Kotlin Sucks". The article doesn't say anything about the circumstances that lead to the sucking (e.g. the main developer suffered a serious brain injury midway through the project) he just lists and details aspects of it that suck.
This incorrect, misleading use of the word "why" in the titles of internet articles is so common I must ask, "why?"
- Some guru years ago must have come up with some over-simplistic silver bullet such as: "if you claim to explain why something is the case in the title, everyone will be drawn in by the potential value you provide and the self-confidence you project". Or some shit like that (case in point - list "articles");
- Copying the linguistic mannerisms of some "in-crowd" makes you feel like you belong. This site is full of ticks like that if you pay attention.
it's possession of said aspects aren't why it sucks?