Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Comparison of Java to Kotlin for various simple methods.

Comparison of Java 7 to Kotlin for various simple code snippets. Files with the same name do the same thing.

/** Returns a subset of {@code list} containing only the items where {@code someBool == true} */
public final List<MyClass> filterList(List<MyClass> list) {
List<MyClass> ret = new List<>(list.size());
for(MyClass item : list) {
if(item.someBool) {
ret.add(item);
}
}
return ret;
}
/** Returns a subset of `list` containing only the items where `someBool == true` */
fun filterList(items:List<MyClass>) = items.filter { item -> item.someBool } // or { it.someBool }
/** Example of a {@link Class} declaration */
final class MyClass {
private boolean someBool;
public MyClass() {
}
public MyClass(boolean someBool) {
this.someBool = someBool;
}
public boolean getSomeBool() {
return someBool;
}
protected void setSomeBool(@NonNull boolean value) {
someBool = value;
}
@Override
public String toString() {
return "someBool:" + someBool;
}
// not shown: .copy override
// not shown: .hashcode override
// not shown: .equals override
}
/** Example of a [Class] declaration. */
data class MyClass(var someBool: Boolean = false)
/** Gets the second character in a string or, if not possible, returns some default value (which may be {@code null}) */
@Nullable
public final String getSecondCharOrDefault(@NonNull String str, @Nullable String defaultVal) {
return str.length() > 2 ? str.get(1) : defaultVal;
}
/** Gets the second character in a string or, if not possible, returns some default value (which may be `null`) */
fun getSecondCharOrDefault(str: String, defaultVal: String?) = if(str.length > 2) str[1] else defaultVal
/** First prints "one dish", then "two dish" */
public final void printRxJavaStuff() {
Observable.from(Arrays.asList("one fish", "two fish", "red fish", "blue fish"))
.filter(new Func1<String, Boolean>() {
@Override
public Boolean call(String s) {
return s.contains("one") || s.contains("two");
}
})
.map(new Func1<String, String>() {
@Override
public String call(String s) {
return s.replace("fish", "dish");
}
})
.subscribe(new Action1<String>() {
@Override
public void call(String s) {
Timber.v(s);
}
});
}
/** First prints "one dish", then "two dish" */
fun printRxJavaStuff() {
Observable.from(asList("one fish", "two fish", "red fish", "blue fish"))
.filter { it.contains("one") || it.contains("two") }
.map { it.replace("fish", "dish") }
.subscribe( { Timber.v(s) } )
}
/** Returns {@code "yes"} if {@code value == true} or {@code "no"} if {@code value == false}. */
public boolean yesOrNo(boolean value) {
return value ? "yes" : "no";
}
/** Returns `"yes"` if `value == true` or `"no"` if `value == false`. */
fun yesOrNo(value: Boolean) = if(value) "yes" else "no"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment