DEV Community

A small piece of code which is going to inspire you to try out Kotlin

Zoltan Polgar on December 07, 2017

A few months ago I’ve started to discover Jetbrains’ Kotlin language which gave a good impression to me. I can't express my thoughts better than th...
Collapse
 
evanoman profile image
Evan Oman • Edited

I love just about everything I have seen from Kotlin, but the snippet you added can be closely replicated in Java 8:

public static void main(String[] args)
{
    /* Init Map */
    Map<String, List<Integer>> myMap = new HashMap<>();
    List<Integer> l = new ArrayList<>();
    l.add(32);
    myMap.put("aaa", l);

    /* New kv pair */
    String key = "aaa";
    Integer value = 2;

    /* Add the new value */
    myMap.computeIfAbsent(key, k -> new ArrayList<>())
            .add(value);
}
Collapse
 
nurettin profile image
Nurettin Onur TUĞCU • Edited

Actually, the java example is better, since the lambda is lazily evaluated. putIfAbsent will always try to construct it's second argument even if it isn't in the map. However, that doesn't mean you can't use it in kotlin as well.

Collapse
 
pozo profile image
Zoltan Polgar

Hi Evan, thank you for this snippet! I wasn't familiar with computeIfAbsent method. :)

Collapse
 
evanoman profile image
Evan Oman

No problem! It is amusing watching Java add a lot of these kinds of features from Scala and Kotlin.

Collapse
 
florianschaetz profile image
(((Florian Schätz)))

Java 9 will also have some nice factory methods, so you will probably be able to write something like...

Map map = Map.of("aaa", List.of(32) );

Collapse
 
bgadrian profile image
Adrian B.G.

I don't think that this is a good example, this hacker type/python style code is not good for anyone, is hard to understand, maintain, extend, catch errors and so on. The first snippet can be understood by most engineers that worked in any C like language, the 2nd ...probably under 10%.

I'm more interested when Kotlin will be able to build iOS apps, then it will be on my radar (shooting 2 platforms with 1 language).

Collapse
 
theodesp profile image
Theofanis Despoudis

hacker type/python

Excuse me are you saying that all Python Programmers are hackers that write bad code that is hard to understand, maintain, extend, catch errors etc?

Collapse
 
lukaszwiktor profile image
Łukasz Wiktor • Edited

I see 2 identical code snippets...

Collapse
 
lukaszwiktor profile image
Łukasz Wiktor

Ok, I see it's been fixed.

Collapse
 
jangalinski profile image
Jan Galinski

Not for me, I still see the Lazymap.java twice

Thread Thread
 
lukaszwiktor profile image
Łukasz Wiktor

It may be something wrong with the dev.to platform. Looks like it's serving previous versions of the post occasionally. Sometimes I'm getting this post loaded without the second snippet at all.