Skip to content

erdemtopak/kotlin-cheat-sheet

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 

Repository files navigation

Kotlin Cheat Sheet

1. Constructor

Extend a class which has multiple constructors.

open class Parent {

    constructor(name: String) {
        //...
    }

    constructor(name: String, surname: String) {
        //...
    }
}

class Child : Parent {

    constructor(name: String) : this(name, "") { //Calls the constructor below
        //...
    }

    constructor(name: String, surname: String) : super(name, surname) { //Calls Parent's constructor
        //...
    }
}

Chain constructor code can be generated by Kotlin with @JvmOverloads annotation

Assume that we have a class Person written in Java.

class Person {

	Person(String name) {
		this(name, "")
	}

	Person(String name, String surname) {
		this(name, "", 0)
	}

	Person(String name, String surname, int age) {
		//implementation
	}
}

Kotlin version will be

class Person @JvmOverloads constructor(
	var name: String,
	var surname: String = "",
	var age: Int = 0 
)

About

Kotlin Cheat Sheet

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published