Skip to content

Instantly share code, notes, and snippets.

@wispborne
Last active August 17, 2020 19:42
Show Gist options
  • Select an option

  • Save wispborne/5d7bde79a3967b27d9e25a74bccfdad7 to your computer and use it in GitHub Desktop.

Select an option

Save wispborne/5d7bde79a3967b27d9e25a74bccfdad7 to your computer and use it in GitHub Desktop.
Comparison of Java to Kotlin for various simple methods.

Comparison of Java to Kotlin for various simple methods. Both files do exactly the same thing.

/** Returns a subset of {@code list} containing only the items where {@code someBool == true} */
public 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 {@code "yes"} if {@code value == true} or {@code "no"} if {@code value == false}. */
public boolean yesOrNo(boolean value) {
return value ? "yes" : "no";
}
/** 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 }
/** Returns `"yes"` if `value == true` or `"no"` if `value == false`. */
fun yesOrNo(value: Boolean) = if(value) "yes" else "no"
/** Example of a {@link Class} declaration */
final class MyClass {
private boolean someBool;
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;
}
// .copy override
// .hashcode override
// .equals override
}
/** Example of a [Class] declaration. */
data class MyClass(var someBool: Boolean = false)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment