17 ms·
Kotlin vs. Java
- AndrewBissell 7y agoVery 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
- jermaustin1 7y agoI 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 7y agoIt feels like a common sentiment that concise code == good code
- smt88 7y agoThat's true, and Kotlin definitely leans into it, but extremely concise code basically ends up looking like Brainfuck -- lots of symbols jammed together and hard to read.
- driver733 7y agoTo be more precise, I would say that expressive code == good code
- martin1975 7y agoAs long as expressive doesn't mean too terse and somewhat readable to most...lest you commit perl's sins.
- dajohnson89 7y agoYeah. This was the point I was halfheartedly making -- concise code for the sake of concise code is a dogma that needs to go away.
- rongenre 7y agoWell, more to the point - bugs / LOC is remarkably constant in real code across coding languages, so one of the best things you can do is reduce LOC.
- pkolaczk 7y agoYou're missing the fact that the constant factor differs between languages. The density (bugs per LOC) of memory handling bugs is much different in Rust than in C.
- rongenre 7y agoNope. https://softwareengineering.stackexchange.com/questions/185660/is-the-average-number-of-bugs-per-loc-the-same-for-different-programming-languag https://softwareengineering.stackexchange.com/questions/1856...
- pkolaczk 7y agoThe link you gave confirms what I've said here. > The quote is either wrong or outdated. In the second edition, it's on page 521: "Industry average experience is about 1 - 25 errors per 1000 lines of code for delivered software. The software has usually been developed using a hodgepodge of techniques. 1-25 is not a single number - it is a range.
- mjcohen 7y agoAPL may be a counterexample, at least when trying to understand what you have written a few months later.
- ivolimmen 7y agoWell: less code means less bugs doesn't it?
- tjohns 7y agoThe Elvis Operator is particularly useful because it's such a common pattern in Kotlin, since the language enforces null safety. When you're using a legacy Java API without nullability annotations, the language forces you to explicitly handle a null result.
- vinceve 7y agoIt masks the complexity of your statement. I know in ruby we had the same issues with the “try()” method. Our rule was, do or do not, there is no try. :) More info: https://karolgalanciak.com/blog/2017/09/24/do-or-do-not-there-is-no-try-object-number-try-considered-harmful/ https://karolgalanciak.com/blog/2017/09/24/do-or-do-not-ther...
- benibela 7y agoNo, in that case it does not enforce it The Java types become platform types
- saagarjha 7y agoOn the contrary, I consider the "Elvis operator" to be one logical operation: give me this value, or the other one if this one is invalid. What's the more terse way to write the example with a ternary operator?
- zmmmmm 7y agoThe beauty of the ternary operator is that it isn't one. It's just taking advantage of the fact that if/else is an expression in Kotlin and it turns out that when if/else yields a value, a dedicated ternary operator is redundant. It's one of a small number of things that I like better about Kotlin than Groovy.
- Someone1234 7y agoThat's actually a really clever (yet simple) design. Have other languages done this before? Now I cannot "unsee" that concept. Why isn't if/else an expression in other languages that just yields a value?! That's a powerful idea.
- cesarb 7y ago> Have other languages done this before? LISP. For a more recent example, Rust.
- int_19h 7y agoIt's very common for languages to adopt an everything-is-an-expression concept, and then make if/else the conditional operator.
- nepeckman 7y agoNim does this as well. Almost any block statement (including creating a new scope with `block`) can be put on the right hand side of an assignment. Whatever value is returned from the block is the result of the expression. All lisp inspired, of course, but with a Pythonic syntax.
- virtualwhys 7y ago> Have other languages done this before? Well, yeah, Scala obviously, the primary language from which Kotlin drew inspiration for its syntax and features.
- Drakar1903 7y agoI wonder why people don't frame Kotlin as the middleman that takes the good parts of both Java and Scala.
- leeman2016 7y agoOne obvious advantage of the "if-else" approach is using indefinite "else if" conditions rather than just one "else"
- chrisseaton 7y agoWhy don’t the Java examples use var?
- driver733 7y agoThey will. I am in the process of updating Java code snippets to Java 11.
- vips7L 7y agoProbably should do 13 since it's the current release.
- driver733 7y agoSure, 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.
- hugi 7y agoThen you should really name your article "My Arbitrary Choice of Java versions That I Believe People Use vs. Kotlin".
- vips7L 7y agoYeah 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 7y agoMy 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.
- nostrademons 7y agoThis 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.
- oh-4-fucks-sake 7y agoSo much this. Although if the guide is meant to hit on the heavy-hitter basics, I think it's a great start.
- commandlinefan 7y agoKotlin (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?
- Filligree 7y agoScala is way more complicated. I don't know if that's an advantage or not -- I never got far enough into learning it to do a valid comparison. Kotlin code is something any Java programmer can read with just a few days learning, however.
- bitL 7y agoOK, 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...
- driver733 7y agoI leave it to the reader to decide whether the advantages are clear or not. For instance, in Kotlin you can perform operations on collection without converting them to a stream first, and collecting them with a certain collector afterwards. So in order to perform a single filtering operation on a collection, you need to do three steps in Java and just one in Kotlin. Another advantage is coroutines, which not only allow you to write asynchronous code in a common, synchronous manner, but also get rid of shared mutable state, since coroutines can send/receive shared state through channels.
- deepsun 7y agoThat'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 7y agoOnce 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 7y agoScala is overcomplicated. Java's goal was to get rid of C++ complexity, Scala sneaked it back in.
- xwowsersx 7y agoComparing 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.
- driver733 7y agoIt is, however, even in the scope of the "Hello world" app, Kotlin performs much better than Java in terms of bringing out business logic to the front.
- deepsun 7y agoAnd in IntelliJ you just write "psvm" and hit Tab.
- achikin 7y agoIntellij driven development.
- vips7L 7y agoKotlin is more Intellij driven than Java... There is no official support for anything, but IntelliJ.
- enitihas 7y agoThere is an official plugin for Eclipse.
- pjmlp 7y agoAlways behind InteliJ one, and nothing else for other Java IDEs.
- The_rationalist 7y agoAnd android studio
- JanecekPetr 7y agoThe I/O example is moot since Java 11 where Java got https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/nio/file/Files.html#readString(java.nio.file.Path) https://docs.oracle.com/en/java/javase/13/docs/api/java.base..., 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.
- driver733 7y agoYou are right, but you still have to catch the checked IOException.
- deepsun 7y agoI actually like it. I also create my own exceptions for rare (exceptional) cases, just not to forget to handle them. But some Java SDK exceptions drive me crazy. For example `URL.parse("http://example.com")` http://example.com")` over hard-coded strings that I know 100% won't throw exceptions, but I still to catch 3 of them.
- vips7L 7y ago`URI.create("https://example.com")` https://example.com")`
- twic 7y agoThat's why URI has a factory method that you're only supposed to use for known strings (although of course this can't be checked): https://docs.oracle.com/javase/7/docs/api/java/net/URI.html#create(java.lang.String) https://docs.oracle.com/javase/7/docs/api/java/net/URI.html#... After URI appeared in 1.4, the only reason to use URL was to create a URLConnection from a URI. Since openConnection() throws IOException, it's not a big deal that toURL() throws a MalformedURLException - just catch it along with all the other IOExceptions. Since 11, there's no reason to use URL at all, because you can use HttpClient to actually do HTTP.
- melling 7y agoI 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.
- unnouinceput 7y agoI 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 7y agoAren't they all case sensitive since FORTRAN and BASIC?
- Roboprog 7y agoOnly in the C, C++, Java, ... universe. Worked with a few case smashers in the 80s. Smashing Unicode is hard, I guess. I don’t really have much of a preference for or against case sensitivity, though I do hate fuglyCaps
- klodolph 7y agoPascal, R, Lisp, Ada, SQL are case-insensitive.
- andrewbinstock 7y agoAnd COBOL, don't forget COBOL! ;-)
- ratherbefuddled 7y agoIt's hard to conceive of an issue which is less important in modern programming. In 20 years of commercial programming on a variety of platforms my experience is that case sensitivity causes no problems at all and case insensitivity causes only minor and occasional problems.
- unnouinceput 7y agoI would love to live in your bubble. Unfortunately, or perhaps fortunately, depends on what point of view you refer to, as freelancer in past 10+ years, real life is quite different.
- jeroenhd 7y agoWhy 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 7y agoEven 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 7y agoEven 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();
- nimchimpsky 7y agoWhy isn't anyone using the ternary operator ? return (nullableVariable != null && nullableVariable.someMethodCall()) ? true : fallbackIfNullMethodCall();
- posedge 7y ago
- soulnothing 7y agoAt 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 7y agoI 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 7y agoThread 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 7y agoJava is getting green threads/fibers by means of project Loom. Arguably much more straightforward to use compared to async/await.
- findjashua 7y agothe 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).
- svnpenn 7y agoI 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?
- vips7L 7y agoGraalVM has a native-image compiler. https://www.graalvm.org/ https://www.graalvm.org/
- spelunker 7y agoGraalVM can build native images: https://www.graalvm.org/docs/reference-manual/native-image/ https://www.graalvm.org/docs/reference-manual/native-image/ I haven't heard of kotlin-native, but apparently it isn't using GraalVM under the sheets which is interesting.
- thu2111 7y agoKotlin Native predates the release of native-image. Also it's actually a slightly different language. Kotlin/Native really wants you to not write shared memory multi-threading. All variables are thread local by default. It has special constructs for interop with C libraries, and uses a sort of reference counting Python-esque memory manager if I recall correctly. You can only use C or other Kotlin/Native libraries. GraalVM native images are a different matter. It uses the Java memory model and ahead of time compiles all the code to native. The "VM" part is bundled with the binary but it's very small and thin. Really it's just a simple generational GC and a bit of support for reflection over things you said you want to reflect over. Both produce small binaries that start as fast as C programs do. In fact the GraalVM team have advertised cases where native-image binaries start faster than C programs do.
- saagarjha 7y agoIs this like Graal (e.g. build the VM into the “native” image) or actually compiling to a just a native binary?
- 7y ago
- vmchale 7y agoThe Null II example and the Elvis operator look like special cases of monadic bind/functorial map.
- tdelev 7y agoI 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 7y agoThere 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 7y agoI 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 7y agoKotlin 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.
- 7y ago
- lmaophp 7y agoSolid shit vs liquid shit
- echelon 7y agoAll 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 7y agoBut 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.
- xixixao 7y agoCertainly Kotlin vs Java looks a lot like CoffeeScript vs JS. For one, CoffeeScript had great impact on JS, and still has a few advantages (along its disadvantages). Perhaps Kotlin will play the same role. But I'm doubtful Java can evolve as JS did. For one, the philosophy and speed of development of Java is very different, and kinda set in stone. But perhaps more importantly, types are part of Java, and they need to be backwards compatible. I think this will make it extremely hard to adopt some of the sane defaults from Kotlin.
- Zarel 7y agoHaving lived through the CoffeeScript thing, the main issues were: 1. CoffeeScript required a compile step; JavaScript didn't. It also meant that you needed to do your debugging in JavaScript, and deal with a lot more leaky abstractions. On the other hand, Kotlin and Java both compile directly to JVM bytecode. 2. CoffeeScript had a lot of features that work very unpredictably, like a number becoming an array of numbers if you add more lines at the same indentation level (which also means that your array will surprisingly become not an array if you delete too many entries). A lot of people only used CoffeeScript because there was no alternative, rather than actually liking it, and they were the first to jump ship when ES6 gave them an alternative. Kotlin doesn't have any of these issues. It really is an improved Java.
- dionian 7y agowhat i want to see is kotlin vs scala
- thom 7y agoThere 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.
- zonidjan 7y agoThis seems great. For someone who already knows Kotlin.
- EsssM7QVMehFPAs 7y agoKotline looses me at val vs. var So much focus on readability otherwise, what happened there?
- _akei 7y agoWhenever 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.
- oriolid 7y agoWhat's the difference between ternary operator and inline if/else? Is there even any reason for if/else that doesn't return a value (that may be void/unit/similar)? It is also obvious that Java version of the variable syntax is awful and just asking for unintentional modification.
- madiathomas 7y ago> What's the difference between ternary operator and inline if/else? There is no difference. Ternary operator is a syntactic sugar for if/else. > Is there even any reason for if/else that doesn't return a value (that may be void/unit/similar)? Main reason why an if statement returns a value is because it is used to test if condition is true or false. If it returns other values, it was going to make it more complicated. Especially when you have an if statement with multiple conditions that must be ORed or ANDed. What is awful about the variable syntax? This syntax was copied directly from C language.
- oriolid 7y ago> Main reason why an if statement returns a value is because it is used to test if condition is true or false. Uh, no. The condition itself is true or false. The return value is useful for assigning, passing as parameter, etc. Non-returning if requires dealing with temporary variable, which itself is verbose, doesn't automatically get assigned in both branches, doesn't play nice with C++-style move semantics, etc. > What is awful about the variable syntax? This syntax was copied directly from C language. C language is awful, but at least they have the excuse that nobody knew better in the 70s and const kind of works even the syntax is a bit complicated.
- lenkite 7y agoRaw, multi-line strings are coming in JDK 13 thanks to https://openjdk.java.net/jeps/326 https://openjdk.java.net/jeps/326
- Polyisoprene 7y agoJava 13 was released 2 months ago.
- lenkite 7y agoI am so outdated. (Our company uses an internal licensed version of the JDK and we don't have JDK 13 yet)
- aliakhtar 7y agoIt pisses me off a bit to not see Scala mentioned anywhere. Scala has everything Kotlin has, and a lot more.
- cortesoft 7y agoI am not a user of either, but my understanding is that Kotlin is a lot easier to use with existing Java projects.
- aliakhtar 7y agoAbsolutely untrue, Scala is completely backwards compatible with Java - you can use all your java code in Scala and even write scala as mostly a better Java.
- eganjs 7y agoSadly it is actually the case. I recently worked on a project using the AWS SDK. We had written our code using Scala and had to up version the AWS SDK to 2.0. Because we used reflection with it, we encountered a Scala compiler bug (an illegal cyclic reference) and had to rewrite it all in Java.
- wskinner 7y agoWhich 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 7y agoScala 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.
- aliakhtar 7y agoFor 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_ 7y agoCould 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.
- ulkesh 7y agoI 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 7y agoI 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 7y agoIt’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.
- jariel 7y agoI 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/bluetooth#kotlin https://developer.android.com/guide/topics/connectivity/blue...
- didibus 7y agoTo 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 7y agoI'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.
- KorematsuFred 7y agoA 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.
- balladeer 7y agoThough I do find Java's String concatenation cleaner than Kotlin's (refer: Strings II comparison/example, the 2nd last)
- ljackman 7y agoI 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.
- peter303 7y agoKotlin is people impatient with the glacial evolution of Oracle Java.
- m23khan 7y agoFrankly, 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).
- UserIsUnused 7y agoBackend kotlin is growing fast, not as much as android, but it is growing. You can notice big frameworks all adding kotlin niceties.
- oblio 7y agoYeah, Gradle added support, so did Spring, Micronaut, etc.
- gentaro_ 7y agoI 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?
- eganjs 7y agoI 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 7y agoExtension functions are dispatched statically which can be surprising if you can’t tell what is an extension and what isn’t
- ulrikrasmussen 7y agoKotlin 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 7y agoWell, 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.
- mike_kamau 7y agoKotlin 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 7y agoIt reminds me of moving from VB.Net to C# years ago!
- psychoslave 7y agoNot 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?
- boring_twenties 7y ago100%, who the hell would write if (success) return success. Come on.
- afandian 7y agoHow would you handle the else clause?
- boring_twenties 7y agoThe comment I responded to has the correct way (return success || somethingelse).
- deleted 7y ago[deleted]
- RyEgswuCsn 7y agoWould this work? return Optional.ofNullable(nullableVariable).map(v -> v.someMethodCall()).orElse(false) ? true : fallbackIfNullMethodCall();
- AnyTimeTraveler 7y agoWhy 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.
- afandian 7y agoI 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)
- mrkeen 7y agoIt sounds like you got locked in.
- afandian 7y agoLocked into Java, yes. At some level it's unavoidable, you have to choose some kind of stack. And of course there are different kinds of ways to get out of lock-in. One of them is being able to convert to a common 'lower' language. I've not used Kotlin but I would be more likely to if I knew that avenue was practical.
- thu2111 7y agoThere'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 7y agoThanks for that. I think I'd misread something then and thought that it could work both ways.
- jillesvangurp 7y agoI think the reason a Kotlin to Java converter does not exist is mainly because there's simply no demand for it in the Kotlin community. In my experience it's a one way street and people generally have no desire whatsoever to go back after they start converting Java code to Kotlin. There's nothing particularly hard about it; it all compiles down to the same bytecode. People keep bringing up Scala as a "purer" language. This seems to be true in the minds of Scala purists mainly. I've done Scala, IMHO it's a very messy language that seems to result in unwieldy code bases that was made for wannabe functional programmers that need a halfway house on the way to a proper functional language (like Haskell or Elixir).
- volgar1x 7y agoKotlin 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 }
- nurettin 7y agoOut 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.
- dep_b 7y agoThese 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
- ragnese 7y agoSo 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.
- fiatjaf 7y agoSee also: https://rosetta.alhur.es/compare/Kotlin/Java/# https://rosetta.alhur.es/compare/Kotlin/Java/#