Hacker News new | comments | show | ask | jobs | submit login
Learn Kotlin in Y Minutes (learnxinyminutes.com)
375 points by jakub_g 37 days ago | hide | past | web | 233 comments | favorite

> Declaring values is done using either "var" or "val". "val" declarations cannot be reassigned, whereas "vars" can.

I wonder why they decided on these very mistakable names. Why not const/constant/cons/whatever else just as long it's distinguishable from each other?

In my experience as someone whose been writing scala for a couple of years (which also uses val/var), it has 100% never been confusing or a problem.

Yep. I think the names themselves are quite unambiguous to boot. A variable is something that varies in value, meaning it can be changed. A value is always that same value; 5 is never 6. Pretty straightforward if you ask me.

I'm guessing the parent is just complaining that if you are reading code very fast (particularly if you're browsing repositories on your phone) it is hard to distinguish between "val" and "var."

Let alone type them wrong on a tired night.

Thankfully that would be a simple compile-time error. The message might even be readable.

If you type var and mean val - would there be any error?

(I'm sure that this is just something you need to get used to, I'm merely trying to point out that this could be a silent typo/mistake)

In many cases, you would get warnings when accessing a var that you don't get when accessing a val. Also, IntelliJ suggests converting to val if a var is never reassigned.

As others said, not a problem if you are using an IDE (and a specific one.)

Considering who authored the language, I am not surprised at all.

In actuality it will be extremely obvious in the IDE and the developer would not make this error.

if "val" is a constant, and you try to mutate it later, the compiler will tell you, "That ain't gonna happen."

It's even worse when your primary keyboard is Dvorak!

I second this. Not to mention that you end up using val most of the time in practice, so there really is no confusion.

scala-mode2 (which isn't close to an IDE) also highlights vars in red so it's extra hard to get mixed up :)

I'm personally a fan of the Rust way, i.e. `let` for const bindings and `let mut` for mutable ones. I think it's fairly clear which is which, and having to type four extra characters to get mutability helps reinforce the notion of const being the default choice.

I agree with making mutability require more typing, although I'd prefer going without the redundant `let`.

It's not redundant; for example

  let (mut x, y) = (1, 2);
x is mutable, y isn't.

That is, let is the way that you introduce a new binding, always.

Am I being a complete noob that only knows Python (I am) if I ask: Why do you need to declare that something is a mut or string or whatever? Python doesn't seem to need such extra lines with obvious declarations.

A couple important benefits (there are many others, as well as drawbacks) are

1) the compiler can then warn you when you violate your own declarations before the code is ever run. e.g. it can tell you that you've mutated something you said you didn't want to, or that you've taken the sum of an int and a list.

2) the compiler can guarantee certain things at compile time and thus eliminate the overhead of checking them at runtime. since a value in Python can be anything, before performing a string operation on a string the python runtime must first check that it is a string, while the runtime of a language like rust can assume that it is because that was guaranteed at compile time.

As others have mentioned, the idea is to have the compiler enforce certain things for you to reduce the chances of making an error. One illustrative way I've seen it explained is that if you accidentally make a variable immutable when you want it to be mutable, you get a very straightforward compiler error message saying something like "you can't mutate this variable since it's const; maybe you should make it mutable?". On the other hand, if you want a variable to be immutable but it's actually mutable and you change it, you can end up with all sorts of tricky bugs like race conditions which are much harder to debug.

Dynamic languages can convert types in runtime (so 1 + "f" = "1f") and not so many languages (not only dynamic) cares about mutability.

Supporting an addition operator that accepts mixed type operands has no relationship to being dynamically typed.

From quick check, it looks like Java can do this coercion, and it's not dynamically typed.

This is weak typing not dynamic typing.

1 + f in modern Python results in a ValueError.

Not OP, but why do you need the 'let' at all? Why not x = 7 mut y = 3 ?

Because it's a bit too error-prone:

   mut listOfLeftHandedOralHygienistsInKazakhstan = getThem()
   // several lines later
   listOfLeftHandedOralHygienistsInKazahkstan = getThemAgain()
You thought you were reassigning the mutable variable, but you actually created a different immutable variable.

This can be prevented by having different operators for assignment and re-assignment. Some languages do that: in OCaml / F#, re-assignments use '<-' while declarations use 'let (mutable) x =' (they can't drop the 'let' because they use '=' as the Boolean equality operator).

... and whoops, the next thing you know your left handed oral hygienist has apocryphally crashed into Venus.


My sibling is correct, but also, there are grammar issues with doing it that way. They're not insurmountable, but much, much simpler with the let.

Sure, but Kotlin is more about being explicit and less about evangelizing one style of programming over another. It's very pragmatic in that way. There are plenty of scenarios where you're maintaining local state (properly encapsulated within a class, exposing a functional interface, etc) and you need mutable fields. Even plenty of scenarios where you want to operate on a value mutably in a function and then return it. It may seem confusing at first but in practice I've never mixed the two up.

But this most likely is because Scala uses val/var.

If your 'let' doesn't propagate so that immutable collections are used, it's not very valuable. Just like 'final' in Java doesn't prevent anyone from mutating your ArrayList. Using 'val' instead of something more suggestive like final/const/'not mut' seems a lot nicer to me. (Edit: and indeed Kotlin having "mutableListOf" and "listOf" separation is a good step in readability. The val/var before either of those is less important.)

That's a misnomer, not a misgiving.

val/var/const/whatever only describe the reference, not the value. It doesn't really make sense for that annotation to, say, swivel a collection between ImmutableList and MutableList.

Now, you might be right that it's confusing, this difference between reference mutability and value mutability. I see beginners struggle with it in Javascript's new let vs const all the time.

Even with Object.freeze() it only prevents mutation of the top-level keys.

> If your 'let' doesn't propagate so that immutable collections are used

It does; if you don't use `let mut`, you can't mutate the variable at all, which includes the contents of a collection.

(Given that someone will mention RefCell if I don't, I'll add: "barring unusual trickery".)

> * If your 'let' doesn't propagate so that immutable collections are used, it's not very valuable.*

That's nonsense.

1. You cannot implement immutable collections without `let` / `final`

2. The Java Memory Model has special visibility guarantees for `final` (which does propagate), making it really, really useful

3. Having the guarantee that a certain reference won't change is still useful even if the object referenced is a mutable ArrayList; e.g. ref = null

1. Sure you can, if you have encapsulation.

2. Java does a lot with the keyword 'final'. I guess here you're talking about the concurrency behaviors of it? Does it bother you that you can remove 'final' via reflection?

3. It's still useful (e.g. not needing to use yoda-style ifs in languages where you can assign inside an if expression Just In Case you forget an =), but not very. That's my whole point.

1. the issue is one of visibility; e.g. you can initiate and pass / share String objects safely between threads without synchronization or worries because underlying String there's a final char[] backing it.

What `final` guarantees is that the variable will be initialized and visible (along with all its referenced objects) before the class constructor is finished. Without this guarantee you'd need `volatile` semantics or locks, which are more problematic.

2. yes, I'm talking about multi-threading; if the user removes "final" via reflection, or modifies final references via reflection, then it gets what he's asking for; but no, it does not bother me because I never do that and I stay away from libraries using reflection anyway.

I thought that's how the majority of languages worked. It just means the variable cannot be changed to reference a different value. It does not make the value immutable.

It really depends on the language. 'const' in C works differently from 'const' in other languages (even C++, which has some great 'const' use cases that make guarantees about whether values will change, not just about the symbol binding), they both work differently than 'final'. Similar confusions with 'static'. If all you want to say is "cannot reassign this symbol", then 'val' is great and sidesteps this whole history of readability and meaning confusion.

In Rust, it does (in general) make the value immutable. Most mutations of values in Rust are done through mutably borrowing the value, which you can't do when the value is defined with `let` rather than `let mut`, the exceptions being things like `Mutex`, which gives you a value that can be mutably borrowed when you acquire the lock.

Kotlin as a language has expectations on IDE capabilities. I doubt the problem of accidentally typing "r" instead of "l" at the end of a keyword is as prevalent as someone typing "var" instead of "const" and not coming back to make it immutable. A quality compiler can warn about an unmutated mutable variable which solves all problems.

Remember recently on the Java mailing list there was a lot of bikeshedding concerning this point. I don't think it matters near as much as the discussion surrounding it thinks.

Oh, and finally, "const" has a specific meaning: compile time constants.

The problem isn't typing, but reading.

Maybe other people's brains work differently than mine, but I'm sure I will be slightly slowed down by this.

When it comes to reading it is very clear in the IDE. val variables look normal (since immutability is encourage), var variables are underlined. You get used to it very quickly

That does help a lot.

I'm happy to be dependent on my IDE.

my beef is with 'val' being keyword. How many variables did you name val in all your coding? I certainly did.

`val` is never an appropriate name for a variable because it tells you nothing at all about what the variable contains.

Except when iterating through a hash, where 'key' and 'val' are my go-to names for stuff

Just use 'value'.

Only you can be sure of shortened words even if it looks obvious. Not good in a team.

I never understood people who shorten words to make the program look cryptic. Maybe it was someone who taught you how to program had it that way or somehow it makes you feel your program looks cooler if it looks more cryptic.

Agreed - at that point, I don't know why you wouldn't just (consistently) use 'k' and 'v'. 'val' adds some weird cognitive load, to me.

'value' is frequently a keyword or property on objects, and has specific meaning in a lot of contexts. For names, IMO 'k' and 'v' also work, but I find an abundance of single-letter variables hard to read. key and val it is.

I dunno, I am horizontally challenged. I like condensed code style like minimizing words, 2 spaces for indent, etc.

never is strong requirement. maybe it doesn't need to tell. Int::add(int val)

I tend to use `num` in those spots.

`val` isn't the variable name, it's the declaration. I'd imagine `val multiplier = 2' to make perfect sense. `var` likewise doesn't connote any truly valuable information other than the label for the memory location that follows is mutable.

None. However I have used 'value' for iteration when I couldn't think of anything better.

I alway use (key, value) or (k, v). :p

I find this syntax very clear, usually start with val and try to stick to it. Moving to var is one char-change only. Also val stands for "value" which is a well known term for immutable data. I think about const as static values, while val are instance values.

My guess is it came from Scala? In practice it's not very tough to get it right.

Val might have originally been OCaml or Haskell.

Standard ML, rather.

It might have appeared in earlier MLs as an extension.

And I was soooo close :)

I mean the combination of val (immutable) and var (mutable) as keywords to declare bindings. OCaml uses let and so does Haskell, right?

It's obviously very strongly influenced by Scala, to the point of adopting a number of its syntax decisions that are considered questionable (procedure syntax, infix notation, "=" function definitions).

I will echo what the others have said; it's not what I would choose, but in practice it's never been a problem when I'm writing Scala.

Why are Scala's "=" function definitions questionable? It makes absolute sense since a function should return a value.

For the same reason omitting braces in C-style-syntax conditionals and loops is questionable, i.e. misleading indentation.

As a bit of an unreformed code golfer and a fan of ML-style syntax, I actually kinda like it myself; I was just listing a few things that are "considered questionable" (by some people) and present in both languages.

They might be referring to the update methods:

  val array = new Array[String](10)
  array.update(7, "hello")
  array(7) = "hello" // simply calls out to update

I still fail to see what makes this questionable. It's just syntactic sugar that you don't even need to use, and which is pretty clear when you see it in the wild.

Oh yeah I don't think it's questionable at all, just guessing what they're talking about.

I'm guessing here: With const there's always the disccusion about consts not being constant, e.g. when referencing an array or object (reference itself is constant). With "val" you don't have that confusion?

But why not let? Or any word that doesn't start with "va"?

I've been writing Kotlin for a year and a half and it has yet to be an issue.

Probably because that's what scala does

This is the usual first thought of someone who's never used the language. A few hours after writing some Kotlin code, you don't even think about it.

Const exists too, but for compile-time constant. Var and val are ok due to the general conciseness of the language (they don't get lost in the noise of other ceremonies). Plus, being a language though to benefit from strong tooling, IDE's will generally display the two differently.

Rust has a pattern-matching "let" and then you can prefix names within any pattern with "mut" to make it mutable. So a basic mutable var is "let mut" but it's just a combination of two other features. I think it's a totally neat design.

With an IDE you could apply different highlighting styles to the two to minimize confusion.

I bet you can change the val color to something that contrasts the var color in an IDE.

The IDE underlines mutable variables at both definition and use sites. Values are not underlined. It's a perfectly fine way to visually distinguish them.

var = variable (can vary/change)

val = value (constant)

What can be mistaken?

Pet peeve here: "variable" and "mutable" aren't concepts that are useful to conflate. Imagine a function that takes a variable and prints its value to the command line. There's no mutation of the variable going on, so the variable is immutable. And yet it's still a variable because each time that you call this function, the value that gets printed is allowed to vary. This is distinct from a constant, where each time you call the function the value of a constant must be the same.

At a quick glance one might mistake var for val since they're only one letter apart. The definitions do make sense though.

I don't find it to be confusing but you'd get more autocomplete help if let was used for constants.

l => let

v => var

Very good point. Fortunately, it's only one keystroke saved.

One keystroke, not two? I type l<tab> in Xcode then I'm typing in the variable name. You'll have to arrow down if it's the wrong one then hit return.

You can argue that it's really not much extra work but it all adds up. Especially when you try to code on a tablet, which I find myself doing occasionally.

It could be two if it inserted the space for you!

The look?

value as being immutable is a common idiom

I like kotlin a lot, but suddenly there are a lot of articles in the front page about it. Kotlin isn't more cool because Google announced yesterday it is going to use it in Android. Kotlin is the same good language it was 2 days ago! (rant over)

If you want to learn kotlin go to the official docs and tutorial, they are as good as the language:


And you don't need to install anything as you can try it in the browser:


The language itself isn't 'more cool' or better, but the risk profile of adopting it has dropped dramatically. That makes it much more interesting.

My team of consultants will write Android apps, and the customer takes ownership of the code base when we're done.

My wife would leave me if she knew how much I love Kotlin, but I could never use it for work projects because we just could not justify expecting random inheriting developers to know Kotlin and accept its legitimacy. That constraint lifted in an instant. It's a political thing, but it really matters.

There weren't any risk before apart form the kotlin plugin not working with beta versions of the gradle build plugin. Using kotlin in Android is like using a library, and you don't have official support from Google for all popular libraries used in Android.

The risk was that you might end up with a code base that you cannot find developers that will work on it/maintain it in the future. The Android support should pretty much guarantee that there will be enough developers familiar with it in the future.

If you are an Android developer you should be aware of kotlin long time and and also tried and use it. Good Android developer knew kotlin before, now you will face more noise to find them.

It is like hiring something who doesn't know the most used libraries in Android. And the risk is exactly the same. The language is not difficult to learn, not much more than a mid-complex library.

But Kotlin was farrrrrrrrrr from a "most used library". The risk of an unsupported language being used is much, much greater than using an unsupported library. Libraries are non-trivial to remove from your code, but should not be tied to your code to the point that you will be required to completely rewrite your application like you would if you ran into issues with the language it's written in.

Say so to the people who is using RxJava or similar, whether they need to rewrite everything or not. In every program you need to take architectural decisions that affect how everything is build and a change on them could mean to rewrite everything. It can be a library or the programming language.

JetBrains was supporting kotlin for Android, the same people that build IntelliJ idea (the base of Android Studio). But who is supporting RxJava? Imagine that the react community wants to make a move that will harm Android devs, so they change all the Rx*, including RxJava.

Using kotlin wasn't a risk. Google said it will make it first class citizen, but do you really trust Google in the long term? They close products very quickly. I feel safer knowing that JetBrains is behind kotlin and not Google.

There are risks other than just not being able to build it.

If I have an app with a codebase in a language that very few people know, that's a risk. What if my main developer leaves and I need to find someone else to continue working on the code base?

You can now bet that a lot of people will be picking up Kotlin as a result of the latest announcement.

Official support still matters. There is some inherent risk whenever you go in a direction not explicitly supported by the owner of your platform, and now that risk is gone.

Not only does official support matter, it matters much more than whether or not the language is good. I keep learning that lesson again and again in the hard, painful way.

As a new developer I'd like to hear more about why this is?

If a language or tool is officially supported, then that means the project maintainers (Google, in this case) promise to support its use with official documentation, priority bug fixes (for example, if an Android update breaks your app which is written in Kotlin and uses only public, non-deprecated APIs, Google will consider it just as high-priority a bug as if it were written in Java), and first-class access to new APIs as soon as they're created.

JetBrains is doing this, not Google. Google is only going to collaborate with JetBrains to help with the Android support.

> Android update breaks your app which is written in Kotlin

then it also breaks the same app written in java. Because the good thing about kotlin is that it is transparent, it generates bytecode as java does. So from the point of view of the platform there is no difference between kotlin and java.

> first-class access to new APIs as soon as they're created.

This makes me think you don't know how kotlin works. You can mix java and kotlin files in the same app and call methods from one to the other without problems.

> JetBrains is doing this, not Google. Google is only going to collaborate with JetBrains to help with the Android support.

Jetbrains isn't doing anything differently with Kotlin from what they've been doing for the past 7 years. The headline here is "Google officially supports Kotlin on Android," and that is what has HN so excited. Regardless of how the work involved in supporting Kotlin on Android is split, this represents a guarantee that did not exist before. If all Jetbrains employees were abducted by aliens tomorrow, Google will now still have committed to first-class support of Kotlin through the next couple of major versions of Android.

> then it also breaks the same app written in java. Because the good thing about kotlin is that it is transparent, it generates bytecode as java does. So from the point of view of the platform there is no difference between kotlin and java.

They share the same compilation target, not the same semantics and idioms. Just because Go, Haskell, C and LuaJIT all target x86 assembly does not mean a Linux kernel update won't break a properly-written program in one of those languages but not the others. This in fact happens all the time.

> This makes me think you don't know how kotlin works. You can mix java and kotlin files in the same app and call methods from one to the other without problems.

I was answering their question generically. But first-class official support means that, for example, if Google adds a new feature to the [Java] Android Runtime, they will, where relevant, now ensure it's implemented in the official Android Kotlin compiler as well as the Java compiler.

> "Google officially supports Kotlin on Android,"

It is JetBrains who support it, Google is only going to collaborate with them to help them out and keep the support up to date.

You don't have any idea about kotlin, the API is exactly the same. It is the Java API for both Java and Kotlin. The support is more related with the tooling, no with the API.

Go, Haskell and C are completely different things. Java and Kotlin compile to bytecode and the JVM runs the bytecode. Both uses the same API in the same language (the bytecode). You only have to guarantee they target the same bytecode version, which is something Google cannot do anything about, it is JetBrains who decide. This is not like Java and C in Android. C has its own API which calls the Java API. Kotlin uses the Java API, and the JVM in the Android device doesn't know if the app was written in Kotlin or Java.

P.S. Actually Android doesn't use the compiled bytecode directly as it make some modifications, but the idea still applies.

Out of curiosity, What was your bad experiences?

You can use kotlin for more things than just Android. And before it had official support from JetBrains (for Android among others). The way it works in Android doesn't make any difference with other popular libraries as retrolambda, picasso, dagger, etc. Those aren't supported by Google and still used in a lot of Android apps.

Google only said they are going to collaborate more with JetBrains, which in my mind it translates in "we, developers, are not going to have incompatibility issues between kotlin and beta versions of the gradle plugin". (I want to highlight the word beta, because with stable versions it was weird you have any issue with kotlin).

I don't think people are saying it's more cool, but the announcement sure made it more known. I'd never heard of it before the announcement (I don't do anything with the JVM these days, so I'm not up on it).

It IS cooler, because everything that Google touches becomes gold, according to HN.

google gets a ton of criticism here

It looks like there's been a very conscious effort to strike a midpoint between Java's familiar clunkiness and Scala's hipster experimental side.

I think that's a good thing, you end up with a language that feels pragmatic and powerfully practical.

Which is funny, because Scala is a pragmatic mix that's halfway between more "pure" functional languages and Java. Guess the sweet spot is a quarter of the way there, not halfway. :)

I've been told that a big selling point for Kotlin is that it was developed from actual usage and production rather than some of the more academic languages solving abstract (although still interesting) problems that day-to-day developers may not care much about.

The Henry Ford quote about faster horses comes to mind.

You're trying to tell us that Scala is something better and we are just too stupid to understand it's power/beauty/importance?

Scala is undeniably more powerful overall (beauty and importance are subjective).

It's also used by companies like Verizon, SAP, IBM, Walmart ... not exactly hipster research labs.

In terms of why we'd want to, there is this note here: https://kotlinlang.org/docs/reference/comparison-to-java.htm...

Other factors to consider are tools support, how often interoprability with java libraries causes problems. Would be nice to hear from someone who has used it a bit about what the state of these is?

I am a pretty big fan, but for non-Android contexts I still like Scala better for a ton of reasons. I wrote a large Kotlin lib[0] the other day and documented a few annoyances[1] I had with it and the devs were very responsive (though non-devs seemed to pick apart maybe one or two of bullet points to dismiss the entire critique).

In the future I would use Kotlin for any Android need (obviously) and any time where I wanted to be lighter weight than Scala. As for native/JS use, I am waiting on the multiplatform story to materialize more before I have a strong opinion, but I would still go with Scala for how easy it is to develop multiplatform libs/progs w/ JVM/native/JS where I can easily have platform specific pieces. Kotlin is almost there[2], but not quite yet.

0 - https://github.com/cretz/asmble 1 - https://gist.github.com/cretz/2a49514b18914ef09b7c518db6db11... 2 - https://discuss.kotlinlang.org/t/abstraction-w-jvm-and-js-im...

I can talk about this in the context of Android.

First I should point out that many large Android apps are using Kotlin. There is a lot of momentum behind Kotlin on Android, that's why Google adopted it.

Tools support is really good. Jetbrains knows how to create tools and it shows. Using kotlin also shows you how great the android plugin for java is. Nothing major, but little features like shortcuts to create a string/drawable resource are sometimes missing in kotlin. Jetbrains is missing that gap though, and we should quickly reach parity now that the language is officially supported.

Interop with Java is equally great ! Both java & kotlin output bytecode, so they can dialog easily.

Some interop caveats : - sometimes calling java from kotlin is not idiomatic. However nowadays many libs are already offering kotlin bindings and again, this should improve.

- similarly, calling kotlin from java can be a bit awkward syntactically speaking.

- kotlin guarantees nullability behavior, but this can be broken at the interface with java in a couple of cases. If the java code lack @nonnull @nullable annotations, it is up to you to handle their nullability. Similarly, kotlin classes instantiated from java code can mess with nullability. If you data class contains a nonnull property and you instantiate this class with Moshi (a json parser), if the corresponding json field is missing you end up with a null field on a nonnull property.

So it is pretty rare, but you can still end up with some NPE.

To me the most promising aspect seems to be async-await on Android. It'd eliminate so much frustration in developing for that platform.

In general, after bouncing between various desktop, mobile, and web-based technologies, I've come to the conclusion that any binding/event-based GUI system needs some sort of async-await or futures support to be truly workable. Otherwise, performing background tasks without locking up the UI involves way too much boilerplate and tends to blow up the architectural complexity of the application.

What do you think of EventBus on Android versus what you ended up using? https://github.com/greenrobot/EventBus Just looking to learn new things.

I've used Kotlin a bit. I can't say anything bad, things just work. That said, idiomatic Kotlin differs from idiomatic Java, so some wrappers are nice to have. And it's really sad, that Jetbrains ditched idea to automatically infer nullability from bytecode, I hope, they'll revisit this decision in the future.

Come on. This is not about actual production stuff. It's new! It's cool! That's pretty much it.

No so. Many people use it in production. The language has been around for 7 years and a stable 1.0+ release for over a year. It's very much more mature than swift and rust and certainly sibling to go in that regard.

I tried to explain exactly this before and a lot of people didn't get it. 1.0 doesn't mean anything, JetBrains spent so much time to make something stable and good. That is why kotlin didn't suffer of the big changes swift suffered since its 1.0. (because kotlin suffered those changes before 1.0)

not trying to say against Kotlin, but Rust has 2 years after 1.0 :)

Honestly I could never really get into Kotlin. I like the features of the language - and would love to have many of them in plain ol' Java - but the syntax just feels wrong to me and I've not been able to get over it.

I find it a huge improvement over Java, but I wish it would have more syntax sugar for lists/arrays/maps like Swift and dynamic languages do.

The mix of "hip" programming language constructs with unchanged Java verbosity feels weird to me. But if I were making an Android app, I'd definitely try to do it with Kotlin first.

What kind of sugar are you looking for? I'd like to have first-class comprehensions in any language I use, but having decent map/filter/reduce|fold implementations is good enough for the most part.

(1..100).map({ it + 10 })

Doesn't seem so bad.

Mutable hashmap/associative array/whatever literals like:

    var map = {"a": 6, "b": 12}
[Whatever list type is most common/idiomatic in Kotlin] literals like:

    var list = [1, 2, 3]

Plus list/map comprehensions like Python or Haskell, as you mentioned.

Not a big deal or anything. It's only a little bit of extra typing. And the syntax sugar they do add is definitely a massive step-up over Java.

I know it'd be hard to add the map literal syntax since it would clash with Java's normal array literal syntax. And I also realize that Java has a wide variety of container types for a reason, and Kotlin wants to be a subset of and not replacement for Java, so doing this may not make a lot of sense.

I guess on reflection, my complaints aren't really valid given that context. I've just had it ingrained in me to use special characters for basic container types, since Python and JavaScript were my first languages for many years.

While somewhat longer, you do have

    var map = hashMapOf("a" to 6, "b" to 12)
    var list = listOf(1, 2, 3)
This is still not Java-level verbosity.

I like that a lot, but the `to` syntax bugs me. Why not a colon, or Scala's `->`?

You type "->" faster and easier then "to"?

No, but it's visually clearer to me at a glance. It feels weird using letters, let alone full English words, to describe a mapping or anything else that I think a symbol is more suited for.

To me it would feel like assigning a variable with:

   a equals 6
   n equals "A"
Just feels icky, somehow.

Again, that wouldn't dissuade me from using the language whatsoever. It's only a minor irritation.

Because "to" isn't actually syntax at all. It's an infix function that creates a Pair. You can alt-click it in the IDE to go to the definition.

`->` in Scala is also just a method, but I think it's fair to call such things syntax even if they're not true "baked-in" language syntax.

You can even get rid of the final parentheses.

(1..100).map { it + 10 }

Somehow that seems even less readable to me.

This is simply "parentheses in a call can be omitted entirely if the lambda is the only argument to that call." This one feature allows for type safe DSL's which eases GUI construction on Android and other domains. https://github.com/Kotlin/anko/wiki/Anko-Layouts

Its also used for chaining stream code which takes in functions. You get used to this feature very quickly.

I know what it is, I'm just saying that in a Java-esque language, omitting parens for function application feels worse than doing so in eg Haskell or even Ruby.

Swift also supports trailing closures. It's a concept that's become pretty familiar of late.

Never wrote any Groovy? Java developers had no problem picking this style up a decade ago.

Nope, never. Just coming back to the JVM ecosystem, actually, as I've been away since around the Java 7 release time (with the exception of some Jython work).

I think you'll be pleasantly surprised how the ecosystem has changed. Legacy code is legacy code, but Java 8 changed a lot and people have mostly also adapted well to ideas coming out of the Scala / Groovy / Kotlin ecosystems primarily because there is just more of it and it's fairly familiar and common to run across libs and projects written those languages now if you're working in Java.

It's actually "if the lambda is the last argument in the call you can close the parens after the penultimate argument".

AFAIK literals for lists/maps are on their TODO list.

what is not a improvement over java?

Is anybody here using Kotlin for back-end work? It seems like I generally hear Kotlin come up in connection with Android, and less for writing server code, though that's where I'd potentially like to use it.

I've used Kotlin for standalone Java programs, it's great. According to Jetbrains, it's roughly 50%:50% between Android guys and Java guys. I guess, after yesterday announce it'll shift to Android.

For example Spring announced that Kotlin will be first class citizen with next major release. So things are definitely bright on the server side.

I've been doing few projects with it and find it very lovely. Interop with Java works flawlessly in my experiences and RxKotlin extending RxJava makes that side work nicely as well. For one project[0] I used Ratpack as the web tier and that with Guice locked in place very easily. DB side of things I have used Kotlinquery which did its job nicely for my small use case.

In another I used Spring Boot where Kotlin felt like a native in that environment.

I'm guessing if you are building something with ORMs or similar where Java Bean convention is needed, you might lack the beauty of immutability and data classes (there are workarounds though) but other than that most pieces drop in place without a hitch.

0: https://github.com/Xantier/trycatch

Yes. I lead a team that's writing a new piece of what can be thought of as enterprise middleware in Kotlin:


It's a distributed ledger/blockchain system being written for large, conservative banks and is around ~90%+ Kotlin code.

There's not much to say about it, it works fine, I wrote about it here:


I've used it to write a real time HN clone using GRPC. It was a wonderful experience. The Java interop is no joke, it works flawlessly.

When you have the option to use Java 8 without caveats (unlike in Android), the benefits of Kotlin aren't really _that_ visible.

I'm never going back to Java on Android though.

Kotlin's taken over HN.

Deservedly so. It is a great language, and it's backed by the ultra-power JVM. You can use a hipster language with great features and still use JodaTime and maven and all the enterprise stuff that just works.

What exactly make it a great language? What are the advantages compared to Java? I search for it but couldn't find any simple answer to that question. The fact that things are shorter to declare doesn't make it better. It makes it less readable.

I haven't used Kotlin, but glancing over their comparison page the one that jumped out to me was that it (almost) eliminates the possibility of null pointer exceptions: https://kotlinlang.org/docs/reference/null-safety.html

This is my litmus test to determine whether a modern language is not terrible. Why wouldn't you want to eliminate an entire class of errors?

Unfortunately, my day to day language at work is Go.

This is like an entry-level expectation for a modern language. Hardly something to write home about in this day and age.

It is when you bring it first-party to a platform the size of Java.

The userbase of Objective-C was much smaller before OSX brought Cocoa to the Mac ecosystem.

> The fact that things are shorter to declare doesn't make it better. It makes it less readable.

That's not a hard and fast rule. There are obvious inflection points. A 200 character long identifier is less readable than a 20 character identifier in almost all cases. A 1 character identifier is less readable than a 8 character identifier in almost all cases. Somehwhere between those extremes is the sweet spot, and it's likely somwhat different depending on person.

As for language keywords, as long as they are unique, unambiguous, and not likely to conflict with written code often, shorter is likely better since it's purely a matter of learning them when learning the language. Given those constraints, it's easy to see it's possible to be too short though (any single character keyword that is not context sensitive is likely a horrible choice).

OK. Let's start writing 1 letter variables then. Shorter code. Better code.

The only way this comment makes sense is if you completely misunderstood what I said.

A wide array of quality of life changes to Java.

> The fact that things are shorter to declare doesn't make it better.

This is debatable. In fact, shorter code could (but not always, of course) mean less room for error and more room to hold higher abstractions. Boilerplate is a less efficient use of cognitive energy.

Agreed, with an exception of magic non-standard out-of-context characters (#$=%>^<) with non-intuitive language-specific meanings; see bash, perl, angular... I prefer short textual keywords 99% of the time

For advantages (and some disadvantages!) compared to Java, I'd start with https://kotlinlang.org/docs/reference/comparison-to-java.htm....


Probably a spike in interest/activity/articles because of Google's announcement that it now is officially supported on Android.

Also because some of us absolutely needed a break from java.

Still looks like Java.

Not even a bad thing. It's a pragmatic JVM language. It's 100% interoperable with Java without baggage like Groovy has. It's probably going to look like Java. Scala can look like Java if you write it very imperatively. What's nice about Kotlin is that the language supports idioms that allow you do diverge from "looking like Java" as you write it more.

Hope we never see "looks exactly like Java syntax but behaves differently when you run it" like we see in Apache Groovy, e.g. their == operator acts differently to Java's.

Pretty much every language's `==` operator acts differently and more sanely when compared to Java's.

Groovy had a very different initial design philosophy compared to Kotlin. The Groovy design philosophy was give Java developers a good highly-dynamic scripting language that still felt like Java but also made it more suitable for writing quick and dirty plugins, scripts and other extension bits to Java programs.

Kotlin is more in the "Java is great already, but has a lot of legacy issues, let's take all the stuff learned in the last two decades and make a Java++"

It's OK for a JVM language to define things differently to Java but still "feel like Java", but it should also have enough syntactic differences so programmers know it isn't Java. The Wikipedia page for Apache Groovy says "Most Java code is also syntactically valid Groovy, although semantics may be different" which isn't a good design.

Kotlin does precisely that, I'm afraid. :P

`a == b` compiles to `a.equals(b)`, if you want reference equality you need to type `a === b`.

Not past the first day. Kotlin code can be beautiful, and I've yet to see beautiful Java code.

Right off the bat, rolling nullability into the static typechecker is a significant break from Java.

Steve Yegge drops a blog post, and we all freak out :) He needs to get back on a regular scheudle so we can react like reasonable people to the next one.

I like this

    val z = (1..9).map {it * 3}
                  .filter {it < 20}
                  .groupBy {it % 2 == 0}
                  .mapKeys {if (it.key) "even" else "odd"}
I'd like it more if it said it performed the functions in parallel. If it does this Automagically I'm sold. If it doesn't, is there an easy to use form that does do batch operations like map in parallel?

Parallel version:

           .map { it * 3 }
           .filter { it < 20 }
           .collect(Collectors.groupingByConcurrent(Function<Int, String> { 
               if (it % 2 == 0) "even" else "odd" 
The result is of type ConcurrentMap<String, MutableList<Int>>

A couple of notes about this code:

1. It uses the Java 8 streams API. I'm not sure it'll work on Android. The code you gave uses the Kotlin standard library extension functions, which is a different implementation of map/filter/etc using inline functions. When possible, use the Kotlin versions, which don't create new garbage or methods. But Kotlin's library is less powerful than the Java streams API, which can do automatic parallelism.

2. For this toy example the parallel code will be slower. There is a cost involved in automatically parallelising an operation that won't even begin to pay off until you're working with very large inputs.

3. Due to a bug in how Kotlin's type inference interacts with the Java 8 Streams.collect call, I have to specify the type of the lambda explicitly, which is a bit ugly. Especially as the IDE and compiler don't quite agree, so the IDE renders Function<Int, String> in grey, but if I remove it as suggested, I get a compile error. Such bugs are very rare (in fact Streams.collect is the only place I've seen it happen lately), but do highlight the fact that Kotlin has only been at version one for a year and is still maturing the level of stability you would expect from Java.

Scala has parallel collections that allow for this, looks exactly the same syntax too.

I guess they're just showing off mapKeys, but couldn't that line be eliminated with:

  .groupBy {if (it % 2 == 0) "even" else "odd"}

No, not parallel. Though it should be possible to add extension functions to Collection that use Java 8's Stream apis to provide that functionality.

You should try LINQ on C#.

Been watching Kotlin for a long time. Usually it pops out when I talk about how great Scala is, and I get Kotlin as "what Scala should have been". I have been avoiding using it at work instead of Java/Scala just because Scala had more "buy in" and it was easier to convince people to try it. Now with the new Google/Android (and HN) love, this is the perfect time to give it another try.

Does Kotlin have algebraic types? Possibly via sealed traits or the like, similar to Scala?

Kotlin has sealed classes. It also has built in generic Pair and Triple containers. But no it doesn't really have algebraic types as you see in Haskell. For example, you can't build a linked list by `cons`ing Ints and Strings and then take the dot product with another Int-String list. It still relies on generics in that regard although it does make improvements with reified types (generics that are retained at runtime for use in type checking `is`--kotlin `instanceof`) and variance indicators.

I have to damit, I wish Ceylon would have won, hehe.

> If a lambda has only one parameter then its declaration can be omitted (along with the ->). The name of the single parameter will be "it".

> val notPositive = not {it > 0}

This idiom took me by surprise. It's really quite lovely, and now I'm disappointed C# doesn't include it.

The schools for and against anaphoric syntax constructs are pretty divided 50-50. "It" is certainly better than scala's underscore.

I'm a bit disappointed that there's no metaprogramming support in Kotlin. Even Groovy had some AST-level transformators. Maybe we'll get some high-level API for writing APT-level tools in Kotlin itself ...

Maybe inline functions may be used for some basic metaprogramming, but I'm not sure https://kotlinlang.org/docs/reference/inline-functions.html

If you're looking for metaprogramming on the JVM, and like the semi-functional approach of Kotlin, you should definitely take a look at Clojure.

I hate clojure, but that complaint is EXACTLY what I was thinking must drive clojure users to it in the first place. Clojure just seems dumb because the jvm is such a hassle and bloated, sbcl is incredible, racket is good, guile is incredible, etc plenty of other lisp environments, why waste time on java?

I hope kotlin native is as good as scala native. I don't care about kotlin vs Java, but kotlin vs scala native is HUGE to me.

To a first approximation, it seems like

Java : Kotlin :: JavaScript : TypeScript

This seems like a good idea.

Kotlin is the new Swift/Golang #hype

Not really, it's more like "Oh my god we don't have to use Java any more". I don't think it is particularly loved on it's own, it's just much better than Java.

Swift is similar in that iOS developers don't have to use Objective C any more, but actually looks like a nice language in its own right.

I think although Kotlin is going to be an improvement for Android development, it's not going to change much unless Google drastically simplify the actual Android API. You're still going to have to deal with this shit: https://github.com/xxv/android-lifecycle

Wasn't scala supposed to do that?

More like coffeescript for Java

Which died. More like TypeScript.

Does it have an equivalent to Swifts if let clause?

    if let person = selection?.organization?.owner {


    val person = selection?.organization?.owner?.let {

You may use `also`. It is like let but it returns the receiver.

    val person = selection?.organization?.owner?.also {

You can use `also` instead of `let` to remove the last `it` line.

ok so I'm guessing you can't operate on more then one scope at once?

    if let person1 = dashboard?.owner, person2 = selection?.organization?.owner {

You'd use nested let clauses and name the param instead of using the implicit "it"

Or just write a function to accomplish the same behavior: http://stackoverflow.com/a/35522422/364135

Would be nice if there was a multiLet in the stdlib. Probably something that happens eventually anyways.

Is this setting a value to the name `person`? What is the value?

selection?.organization?.owner is an optional value, meaning it might be nil/null. That "if let" basically says if it's not nil to assign its value to "person" and execute the block. Then inside the block you can treat "person" as a non-optional, known value.

This webcomic explains it better than I ever could: http://abstrusegoose.com/249

Tried Kotlin few days ago. Started from "official" install docs and it said that it's just 'brew install kotlin". Yeah, it worked just fine but it would have been way nicer if they would have mentioned that you should also have Java 1.6 for compiler to actually work.

So with python I have virtual env. With elixir I have mix. For javascript I have npm.

What do I have for kotlin?


I think the language is quite nice but the tooling is lacking (if you don't use intellj idea). Even the official eclipse plugin has many rough edges. So, when learning kotlin, you effectively also have to learn an ide if you're not already an idea user.

It's interesting how many language wants to be part of the ML family or at least look like an ML language.

Kotlin has a really nice and simple syntax compared to Scala, which has way to many features.

Kotlin is more than just simpler java-syntax, though. If you want to really take advantage of it, there's new idioms, you can use it as a typesafe dsl etc.

Easier syntax??!!

Could someone paraphrase the argument for learning Kotlin? I understand it's essentially Jetbrain's fork of Java, motivated to some degree by the desire to provide useful realtime information to programmers working in the Jetbrains ecosystem. Presumably this implies that certain features present in Java that are ambiguous at compile time (e.g. generic types) might be winnowed away in the pursuit of a language more conducive to static analysis?

It’s not a fork of Java, it’s a language that uses the JVM like Scala. It’s not at all like Java, it’s a modern language more akin to Swift with lots of syntactic sugar.

Does Kotlin have its own class/libraries or it still uses Java's classes?

Kotlin has its own standard library

It's both.

Kotlin's standard library is tiny. It consists mostly of extension functions and aliases over the Java standard library. For instance kotlin.String is just an alias to java.lang.String, it's exactly the same object. Kotlin's lists are just more type safe views over java.util lists. Much of Kotlin's standard library is in fact inlined and then optimised, so using it doesn't even create function calls in your bytecode.

So whilst Kotlin does technically have a standard library, to do anything practical you'll be using Java's. And that's one reason why we like it. No duplicate standard library to learn.

Does anyone know the official docker image for Kotlin or are we too early for that?

I knew this will show up ASAP I heard the Kotlin support news :P

Language quibble:

> "Function arguments are specified in brackets after the function name."

No they're not! They're specified in PARENTHESES after the function name.

the whole kotlin debate is just a misguided stab at solving the pain that is programming for android.

everyone everywhere hates android dev work. so they think that it must be java. no, java sucks, but kotlin sucks just the same. the problem is the android ecosystem as a whole. the ever changing apis. etc.

wasting time on java vs kotlin is absurd with so many other real problems.

Probably everyone will try to hide your comment but that's the truth, there hasn't been a worse ecosystem than Android, learning the Android SDK it's so painful that even if they choose a decent language like Python to support it won't change the fact that the APIs would still be called in the same way, just look at the examples, same just sugar-coated flavor: https://github.com/JetBrains/kotlin-examples/blob/master/gra... vs https://github.com/JetBrains/kotlin-examples/blob/master/gra...

What is wrong with that example?

It is 98% scaffolding and ceremony. The exposed android API is just red tape, that is exposed for no good reason. Good API only expose what matters.

God, what a useless post. If you don't like Android development don't waste your time with it.

Criticism can be useful if constructive.

But that criticism wasn't constructive, so...

it was constructive in the sense that the debate waste time from the real issue. But feel free to keep adding noise and fighting for syntax sugar.

Kotlin - The Force Awakens

Kotlin - The Source Awakens

Haha this one is even better.

Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | DMCA | Apply to YC | Contact