Skip to content

Instantly share code, notes, and snippets.

@davidmigloz
Last active April 20, 2021 22:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidmigloz/cab49252b992f1bcc111f69c198cb8b1 to your computer and use it in GitHub Desktop.
Save davidmigloz/cab49252b992f1bcc111f69c198cb8b1 to your computer and use it in GitHub Desktop.
Dart vs Kotlin: classes
abstract class Vehicle {
String brand; // Public
int _year = 0; // Private
int get year => _year; // Getter
set year(int value) { // Setter
if (value < 0) {
throw ArgumentError();
}
_year = value;
}
Vehicle(this.brand);
void honk() { // Public method
print("Tuut, tuut!");
}
}
class Car extends Vehicle with Piloted {
int numDoor;
Car(String brand, this.numDoor) : super(brand);
Car.mustang() : // Named constructor
numDoor = 2, // Initializer list
super("Mustang");
@override
void honk() { // Override method
print("Bepp, bepp!");
}
}
mixin Piloted {
void describePilot() => print('Pilots');
}
void main() {
final myCar = Car("Tesla", 4);
myCar.year = 2021;
myCar.honk();
myCar.describePilot();
final mustang = Car.mustang();
}
abstract class Vehicle(
var brand: String, // Public
) {
private var _year: Int = 0 // Private
var year: Int
get() = _year // Getter
set(value) { // Setter
if (value < 0) {
throw IllegalArgumentException()
}
_year = value
}
open fun honk() { // Public method
println("Tuut, tuut!")
}
}
class Car(
brand: String,
var numDoor: Int
) : Vehicle(brand), PilotedContract by Piloted() {
override fun honk() {
println("Bepp, bepp!")
}
companion object { // Static method
fun mustang() = Car("Mustang", 2)
}
}
interface PilotedContract {
fun describePilot()
}
class Piloted : PilotedContract {
override fun describePilot() = println("Pilots")
}
fun main() {
val myCar = Car("Tesla", 4)
myCar.year = 2021
myCar.honk()
myCar.describePilot()
val mustang = Car.mustang()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment