Learn Kotlin in Y Minutes
learnxinyminutes.com
learnxinyminutes.com
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?
It might have appeared in earlier MLs as an extension.
val = value (constant)
What can be mistaken?
l => let
v => var
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.
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.
Maybe other people's brains work differently than mine, but I'm sure I will be slightly slowed down by this.
I'm happy to be dependent on my IDE.
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.
But this most likely is because Scala uses val/var.
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
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.
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.
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.
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".)
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.
1 + f in modern Python results in a ValueError.
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.
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).
(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)
Considering who authored the language, I am not surprised at all.
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.
val array = new Array[String](10)
array.update(7, "hello")
array(7) = "hello" // simply calls out to updateAs 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.
If you want to learn kotlin go to the official docs and tutorial, they are as good as the language:
http://kotlinlang.org/docs/reference/
And you don't need to install anything as you can try it in the browser:
> 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 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.
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.
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).
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.
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.
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.
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.
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?
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.
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...
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.
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.
(1..100).map({ it + 10 })
Doesn't seem so bad.
(1..100).map { it + 10 }
Its also used for chaining stream code which takes in functions. You get used to this feature very quickly.
var map = {"a": 6, "b": 12}
[Whatever list type is most common/idiomatic in Kotlin] literals like: var list = [1, 2, 3]
etc.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.
var map = hashMapOf("a" to 6, "b" to 12)
var list = listOf(1, 2, 3)
This is still not Java-level verbosity.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.
For example Spring announced that Kotlin will be first class citizen with next major release. So things are definitely bright on the server side.
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.
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.
https://github.com/corda/corda
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:
https://www.reddit.com/r/programming/comments/6bqo7n/kotlin_...
Unfortunately, my day to day language at work is Go.
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.
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.
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).
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++"
`a == b` compiles to `a.equals(b)`, if you want reference equality you need to type `a === b`.
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? .groupBy {if (it % 2 == 0) "even" else "odd"} (1..99).parallelStream()
.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.
> 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.
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.
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
Java : Kotlin :: JavaScript : TypeScript
This seems like a good idea.
if let person = selection?.organization?.owner {
setTitle(person.name)
setImage(person.image)
} val person = selection?.organization?.owner?.let {
setTitle(it.name)
setImage(it.image)
it
} val person = selection?.organization?.owner?.also {
setTitle(it.name)
setImage(it.image)
} if let person1 = dashboard?.owner, person2 = selection?.organization?.owner {
person1.cloneProperties(person2)
}Would be nice if there was a multiLet in the stdlib. Probably something that happens eventually anyways.
What do I have for kotlin?
Kotlin has a really nice and simple syntax compared to Scala, which has way to many features.
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.
> "Function arguments are specified in brackets after the function name."
No they're not! They're specified in PARENTHESES after the function name.
I think that's a good thing, you end up with a language that feels pragmatic and powerfully practical.
It's also used by companies like Verizon, SAP, IBM, Walmart ... not exactly hipster research labs.
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.