Skip to content

Instantly share code, notes, and snippets.

@matey-jack
Last active August 31, 2018 13:53
Show Gist options
  • Save matey-jack/32114c6d2f5c0a51326b80236ea0fb0b to your computer and use it in GitHub Desktop.
Save matey-jack/32114c6d2f5c0a51326b80236ea0fb0b to your computer and use it in GitHub Desktop.
Initialising immutable fields – in a few modern languages
// Java - has not changed since Java 1.0 up until Java 11.
// yes, you need to name each field exactly four times and its type two times.
class Location {
final double lon;
final double lat;
Location(double lon, double lat) {
this.lon = lon;
this.lat = lat;
}
}
// Dart
// fields are still named twice, but this has advantages when adding more constructors
class Location {
final double lat;
final double lon;
Location(this.lat, this.lon);
}
// Kotlin
// showing of its roots in functional programming with "algebraic data types"
data class GeoLoc(val lat: Double, val lon: Double) { }
// the 'data' keyword is not needed for the initializer and definition syntax to work
// but it is very helpful because it creates sensible implementations of equals() and hashCode()
// which need extra work in other languages
// TypeScript
// also only one mention per field: the feature is called "parameter properties"
class Location {
constructor(readonly lat: number, readonly lon: number) {
}
}
// using AutoValue, https://github.com/google/auto/blob/master/value/userguide/index.md
// like the Kotlin "data class" this also gives sensible implementations for equals() and hashCode()
import com.google.auto.value.AutoValue;
@AutoValue
abstract class Location {
static Location create(double lat, double lon) {
return new AutoValue_Location(lat, lon);
}
abstract double lat();
abstract double lon();
}
// using Lombok, https://projectlombok.org/features/Value
// makes fields private and creates getters and no setters,
// automatically creates constructor with all arguments, also creates equals and hashCode()
import lombok.Value;
@Value
class Location {
double lat;
double lon;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment