From Kotlin to Dart 2 Cheat Sheet - Classes

Constructor Call

Kotlin

val file = File("file.txt")

Dart

final config = File('file.txt');

Simple class

Kotlin

class Post

Dart

class Post {

}

Primary Constructor

Kotlin

class User constructor(id: String) {
    var id: String = id
}

Dart

class User {
  String id;

  User(String id) {
    this.id = id;
  }
}

Constant constructors

Kotlin

fun main() {
    val user1 = User("some_id") // data class User(val id: String)
    val user2 = User("some_id") // data class User(val id: String)

    val areSame1 = user1 == user2
    println("$areSame1")

    val anotherUser1 = User("some_id") // class User(val id: String)
    val anotherUser2 = User("some_id") // class User(val id: String)

    val areSame2 = anotherUser1 == anotherUser2
    println("$areSame2")
}

data class User(val id: String)
class User(val id: String)

Dart

main(List<String> arguments) {
  final user1 = const User("some_id");
  final user2 = const User("some_id");

  final areSame1 = user1 == user2;
  print('$areSame1'); // prints 'true'

  final anotherUser1 = User("some_id");
  final anotherUser2 = User("some_id");

  final areSame2 = anotherUser1 == anotherUser2;
  print('$areSame2'); // prints 'false'
}

class User {
  final String id;

  const User(this.id);
}

Final Properties

Kotlin

class User(val id: String)

Dart

class User {
  final String id;

  User(this.id);
}

Optional Arguments in Constructors

Kotlin

fun main() {
    val user1 = User("some_id")
    val user2 = User("some_id", 25)

    println(user1.age) // prints '18'
    println(user2.age) // prints '25'
}

data class User(val id: String, val age: Int = 18)

Dart

main(List<String> arguments) {
  final user1 = User(id: "some_id");
  final user2 = User(id: "some_id", age: 25);

  print('${user1.age}'); // prints '18'
  print('${user2.age}'); // prints '25'
}

class User {
  final String id;

  final int age;

  const User({this.id, this.age = 18});
}

Read-Only Properties

Kotlin

class Rectangle(private val width: Int, private val height: Int) {
    val area: Int = width * height
}

Dart

class Rectangle {
  int _height;
  int _width;

  Rectangle(this._width, this._height);

  int get area => _width * _height;
}

Abstract Class

Kotlin

abstract class Removable {
    abstract fun remove()
}

Dart

abstract class Removable {
  void remove();
}

Interface

Kotlin

interface Removable {
    fun remove()
}

class Post : Removable {
    override fun remove() {
        // TODO: implement remove
    }
}

Dart

abstract class Removable {
  void remove();
}

class Post implements Removable {
  @override
  void remove() {
    // TODO: implement remove
  }
}

Share this: