From Kotlin to Dart 2 Cheat Sheet - Functions

Simple function

Kotlin

fun printHello() {
    println("Hello, world!")
}

Dart

void printHello() {
  print('Hello, world!');
}

Arguments

Kotlin

fun printHello(name: String) {
    println("Hello, $name!")
}

Dart

void printHello(String name) {
  print('Hello, $name!');
}

Default Values

Kotlin

fun printHello(name: String = "world") {
    println("Hello, $name!")
}

Dart

void printHello([String name = 'world']) {
  print('Hello, $name');
}

Return

Kotlin

fun createHelloWorld(): String {
    return "Hello, world!"
}

Dart

String createHelloWorld() {
  return 'Hello, world!';
}

Single-Expression

Kotlin

fun createHelloWorld(): String = "Hello, world!"

Dart

String createHelloWorld() => 'Hello, world!';

Main I

Kotlin

fun main() {

}

Dart

main() {

}

Main II

Kotlin

fun main(args: Array<String>) {

}

Dart

main(List<String> arguments) {

}

Named Arguments

Kotlin

fun main() {
    printHello(name = "Dart")
}

fun printHello(name: String) {
    println("Hello, $name!")
}

Dart

import 'package:meta/meta.dart';

main(List<String> arguments) {
  printHello(name: 'Dart');
}

void printHello({@required String name}) {
  print('Hello, $name!');
}

Generic Functions

Kotlin

fun main() {
    val list1 = listOf(12, 1, 2, 3, 4, 5)
    val list2 = listOf("D", "A", "R", "T")

    val firstItemFromList1 = getFirst(list1)
    val firstItemFromList2 = getFirst(list2)

    println(firstItemFromList1) // prints '12'
    println(firstItemFromList2) // prints 'D'
}

fun <T> getFirst(list: List<T>): T {
    return list.first()
}

Dart

main(List<String> arguments) {
  final list1 = [12, 1, 2, 3, 4, 5];
  final list2 = ['D', 'A', 'R', 'T'];

  final firstItemFromList1 = getFirst(list1);
  final firstItemFromList2 = getFirst(list2);

  print(firstItemFromList1); // prints '12'
  print(firstItemFromList2); // prints 'D'
}

T getFirst<T>(List<T> list) {
  return list.first;
}

Functions as Arguments

Kotlin

fun main() {
    printCalculationResult { 2 * 5 } // prints '10'
}

fun printCalculationResult(function: () -> Int) {
    println(function())
}

Dart

main(List<String> arguments) {
  printCalculationResult(() => 2 * 5); // prints '10'
}

void printCalculationResult(int function()) {
  print(function());
}

Extension Functions / Methods

Kotlin

data class Person(
    val firstName: String,
    val lastName: String
)

fun Person.getFullName(): String {
    return "$firstName $lastName"
}

fun main() {
    val person = Person("Natig", "Babayev")
    println(person.getFullName()) // prints "Natig Babayev"
}

Dart

class Person {
  String firstName;
  String lastName;

  Person(this.firstName, this.lastName);
}

extension PersonExtension on Person {
  String getFullName() {
    return "$firstName $lastName";
  }
}

main(List<String> arguments) {
  Person person = Person("Natig", "Babayev");
  print(person.getFullName()); // prints "Natig Babayev"
}
  YouTube: Coding with Natig

Share on: