Skip to content

Instantly share code, notes, and snippets.

@upeter
Last active October 9, 2020 13:30
Show Gist options
  • Save upeter/fbc642c434ea9c991e789bb218fcec4e to your computer and use it in GitHub Desktop.
Save upeter/fbc642c434ea9c991e789bb218fcec4e to your computer and use it in GitHub Desktop.
//Java to Kotlin Conversion Quizz samples for Java Magazine
//Example 0: Classes
public class Person{
private final String name;
private final int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person(String name) {
this.name = name;
this.age = 0;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
}
//Example 1: Statics
public class MySingleton {
private static final MySingleton instance = new MySingleton();
private final int state = 42;
private MySingleton() {}
public static MySingleton getInstance() {
return instance;
}
public int getState() {
return state;
}
}
//Example 2: Functions / Primitive/Object conversion hell
public static String convert(String value, Function<Character, String> converter) {
return value.chars().boxed().map(i -> converter.apply((char) i.intValue())).collect(Collectors.joining(""));
}
convert("Welcome2Java'sPrimitive2ObjectHell", Integer::toBinaryString);
//Example 3: Nullability
File file = new File("/any/dir/somwhere");
String firstFileInParentFolder =
file.getParentFile() != null &&
f.getParentFile().listFiles() != null &&
f.getParentFile().listFiles()[0] != null ?
f.getParentFile().listFiles()[0].getName() : "unknown";
//Example 4: Extension methods
try (BufferedReader br = new BufferedReader(new FileReader("foo.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
//Example 5: Collections
Map<Character, Integer> characterCount = List.of("Count", "us", "all")
.stream()
.flatMap(p -> p.chars().mapToObj(c -> (char) c))
.collect(Collectors.groupingBy(i -> i))
.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().size()));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment