kotlin-cheat-sheet

所属分类:编程语言基础
开发工具:kotlin
文件大小:0KB
下载次数:0
上传日期:2023-08-20 21:42:36
上 传 者sh-1993
说明:  Kotlin编程语言的备忘单,
(A cheat sheet for Kotlin programming language,)

文件列表:
01_introduction/ (0, 2023-10-04)
01_introduction/01.First Kotlin program.kt (72, 2023-10-04)
01_introduction/02.Get input from user.kt (133, 2023-10-04)
01_introduction/03.Variables and Data types.kt (450, 2023-10-04)
01_introduction/04.Type inference.kt (188, 2023-10-04)
01_introduction/05.Type Conversion.kt (704, 2023-10-04)
01_introduction/06.String templates.kt (136, 2023-10-04)
01_introduction/07.Operators.kt (1387, 2023-10-04)
02_control_flow/ (0, 2023-10-04)
02_control_flow/01.If else.kt (155, 2023-10-04)
02_control_flow/02.Conditional Expression.kt (535, 2023-10-04)
02_control_flow/03.For.kt (164, 2023-10-04)
02_control_flow/04.Range.kt (408, 2023-10-04)
02_control_flow/05.While and do while.kt (294, 2023-10-04)
02_control_flow/06.Break and Continue.kt (331, 2023-10-04)
02_control_flow/07.Exceptions.kt (340, 2023-10-04)
03_function/ (0, 2023-10-04)
03_function/01.Function Declaration.kt (158, 2023-10-04)
03_function/02.Default arguments and named arguments.kt (358, 2023-10-04)
03_function/03. Function Return Types.kt (230, 2023-10-04)
03_function/04.Local and member function.kt (280, 2023-10-04)
03_function/05.Generic functions.kt (91, 2023-10-04)
03_function/06.Lambda Expressions.kt (160, 2023-10-04)
03_function/07.Extension Functions and Properties.kt (356, 2023-10-04)
03_function/08.Higher-Order Functions.kt (426, 2023-10-04)
03_function/09.Operator overloading.kt (398, 2023-10-04)
03_function/10.varargs.kt (322, 2023-10-04)
03_function/11.Infix notation.kt (220, 2023-10-04)
03_function/12.Scope Functions.kt (799, 2023-10-04)
04_collections/ (0, 2023-10-04)
04_collections/01.List.kt (447, 2023-10-04)
04_collections/02.Set.kt (464, 2023-10-04)
04_collections/03.Map.kt (566, 2023-10-04)
04_collections/04.Array.kt (654, 2023-10-04)
05_class_and_objects/ (0, 2023-10-04)
05_class_and_objects/01. Class and object.kt (183, 2023-10-04)
05_class_and_objects/02.Property and methods.kt (561, 2023-10-04)
05_class_and_objects/03. Inheritance.kt (335, 2023-10-04)
05_class_and_objects/04.Interface and Abstract Class.kt (270, 2023-10-04)
05_class_and_objects/05.Polymorphism.kt (391, 2023-10-04)
... ...

Kotlin Cheatsheet

A Kotlin cheat sheet is a quick reference guide that provides a concise summary of the most important Kotlin syntax and features. Most of the content in this cheat sheet has been collected from the official Kotlin documentation while avoiding detailed explanations. This cheat sheet is designed for quick review purposes and not for providing detailed information, so I suggest that you also read the official Kotlin documentation. If there is any issue, please open an issue or feel free to contribute to its expansion. If you'd like to support me, please give a star to this repository. ![Kotlin logotype](https://github.com/alidehkhodaei/kotlin-cheatsheet/raw/main/images/kotlin_logotype.jpg) # Table of Contents - [Introduction](#introduction) - [First Kotlin program](#first-kotlin-program) - [Get input from user](#get-input-from-user) - [Comments](#comments) - [KDoc](#kdoc) - [Variables](#variables) - [Data types](#data-types) - [Type Inference](#type-inference) - [Type Conversion](#type-conversion) - [String templates](#string-templates) - [Character escape](#character-escape) - [Operators](#operators) - [Control Flow](#control-flow) - [If-else](#if-else) - [When](#when) - [Conditional Expression](#conditional-expression) - [For loop](#for-loop) - [Ranges](#ranges) - [While](#while) - [Do while](#do-while) - [Break and Continue](#break-and-continue) - [Exceptions](#exceptions) - [Functions](#functions) - [Function Declaration](#function-declaration) - [Default arguments and named arguments](#default-arguments-and-named-arguments) - [Function Return Types](#function-return-type) - [Local functions](#local-functions) - [Member functions](#member-functions) - [Generic functions](#generic-functions) - [Lambda Expressions](#lambda-expressions) - [Extension Functions and Properties](#extension-functions-and-Properties) - [Higher-Order Functions](#higher-order-functions) - [Operator overloading](#operator-overloading) - [Variable number of arguments (varargs)](#varargs) - [Infix notation](#infix-notation) - [Scope Functions](#scope-functions) - [Collections](#collections) - [Array](#array) - [List](#list) - [Map](#map) - [Set](#set) - [Classes and objects](#class-and-object) - [Classes](#classes) - [Property and methods](#property-and-methods) - [Getters and setters](#getters-and-setters) - [Visibility modifiers](#visibility-modifiers) - [Late-initialized properties and variables](#late-initialized-properties-and-variables) - [Inheritance](#inheritance) - [Interface and Abstract Class](#interface-and-abstract-class) - [Abstraction](#abstraction) - [Polymorphism](#polymorphism) - [Object Expression and Declaration](#object-expression-and-declaration) - [Data class](#data-class) - [Nested and Inner class](#nested-and-inner-class) - [Type aliases](#type-aliases) - [Enum](#enum) - [Sealed class and interface](#sealed-class-and-interface) - [Generics](#generics) - [Delegation Pattern](#delegation-pattern) - [Delegated properties](#delegated-properties) - [Other Topics](#other-topics) - [Destructuring declarations](#destructuring-declarations) - [Reflection](#reflection) - [Annotations](#annotations) - [Packages and imports](#packages-and-imports) - [Null safety](#null-safety) - [Equality](#equality) - [Comparable](#comparable) - [Regex](#regex) - Kotlin Keywords and operators (Document link) ## Introduction Kotlin is a modern, open-source programming language that is used for building multi-platform applications. It is concise, expressive, and powerful, with features such as null safety, extension functions, lambdas, and many others. This cheat sheet will cover some of the essential Kotlin concepts. ### First Kotlin program This is an example of printing "Hello world" in Kotlin: ```kotlin fun main() { println("Hello world") } ``` ### Get input from user To get input from the user in Kotlin, you can use the readLine() function. This is an example: ```kotlin fun main() { print("Enter your name: ") val name = readLine() println("Hello, $name!") } ``` ### Comments ```kotlin // This is an end-of-line comment /* This is a block comment on multiple lines. */ ``` Block comments in Kotlin can be nested. ```kotlin /* The comment starts here /* contains a nested comment */ and ends here. */ ``` ### KDoc KDoc is the documentation format for Kotlin, similar to Javadoc for Java. KDoc is used to generate documentation for Kotlin classes, functions, and properties. KDoc comments start with the /** and end with */. This is an example: ```kotlin /** * Calculates the sum of two integers. * * @param a The first integer to add. * @param b The second integer to add. * @return The sum of the two integers. */ fun sum(a: Int, b: Int): Int { return a + b } ``` ### Variables In Kotlin, variables can be declared using either the var or val keyword. var variables are mutable, meaning their value can be changed after they are initialized. ```kotlin var x = 5 x = 10 ``` val variables, on the other hand, are immutable, meaning their value cannot be changed after they are initialized. ```kotlin val y = 5 y = 10 // This will result in a compilation error ``` ### Data types Here's a brief overview of the most commonly used data types: ```kotlin val booleanVar: Boolean = true val byteVar: Byte = 127 val shortVar: Short = 32767 val intVar: Int = 2147483647 val longVar: Long = 9223372036854775807L val floatVar: Float = 3.14f val doubleVar: Double = 3.14159265358979323846 val charVar: Char = 'A' val stringVar: String = "Hello, world!" ``` ### Type Inference Kotlin supports type inference, which means the compiler can infer the type of a variable from its initial value. ```kotlin val x = 5 // The type of x is inferred to be Int val y = "hello" // The type of y is inferred to be String ``` Variables in Kotlin can also be declared without an initial value, but in that case, the type must be explicitly specified: ```kotlin var z: Double // Valid, z has no initial value // println(z) // Invalid, z is not initialized and has no value yet z = 3.14 // Valid, z is initialized with a value ``` ### Type Conversion Kotlin provides several methods for converting between data types. Here's an example in Kotlin that demonstrates various methods of type conversion. ```kotlin val str: String = "123" val num: Int = str.toInt() // Convert String to Int val dbl: Double = 123.45 val int: Int = dbl.toInt() // Convert Double to Int val lng: Long = 9876543210 val flt: Float = lng.toFloat() // Convert Long to Float val bol: Boolean = true val strBol: String = bol.toString() // Convert Boolean to String val char: Char = 'A' val intChar: Int = char.toInt() // Convert Char to Int // Conversion of Char to Number is deprecated. Use Char.code property instead. val byte: Byte = 127 val short: Short = byte.toShort() // Convert Byte to Short ``` ### String templates ```kotlin val name= "Ali" val result= "My name is $name" ``` ### Character escape ```kotlin \n insert new line \t inserts a tab \r inserts carriage return ``` ### Operators Arithmetic operators ```kotlin val a = 10 val b = 5 println(a + b) // 15 println(a - b) // 5 println(a * b) // 50 println(a / b) // 2 println(a % b) // 0 ``` Comparison operators ```kotlin val c = 10 val d = 5 println(c > d) // true println(c >= d) // true println(c < d) // false println(c <= d) // false println(c == d) // false println(c != d) // true ``` Assignment operators ```kotlin var h = 10 h += 5 println(h) // 15 h -= 5 println(h) // 10 h *= 2 println(h) // 20 h /= 4 println(h) // 5 h %= 3 println(h) // 1 ``` Logical operators ```kotlin val i = true val j = false println(i && j) // false println(i || j) // true println(!i) // false ``` Bitwise operators ```kotlin val k = 0b1010 val l = 0b1100 println(k and l) // Prints "8" (0b1000) println(k or l) // Prints "14" (0b1110) println(k xor l) // Prints "6" (0b0110) ``` Range operator ```kotlin val o = 1..10 println(o.contains(5)) // Prints "true" println(o.contains(11)) // Prints "false" ``` ## Control flow ### If-else ```kotlin if (condition) { // Code to execute if condition is true } else { // Code to execute if condition is false } ``` ### When ```kotlin when (value) { condition1 -> // Code to execute if value matches condition1 condition2 -> // Code to execute if value matches condition2 else -> // Code to execute if value does not match any condition } ``` ### Conditional Expression Given if and when are expressions, we can directly assign them to variables. ```kotlin val seasonFirstMonth = when(season) { "summer" -> 6, "winter" -> 12, "automn" -> 9, "spring" -> 3, else -> error("There is only 4 seasons") } ``` Thus, it allows a similar ternary operator using a regular if. ```kotlin val max = if (a > b) a else b ``` ### For loop ```kotlin for (item in collection) { // Code to execute for each item in collection } ``` ### Ranges There is a set of tools for defining ranges in Kotlin. ```kotlin for(i in 0..3) { print(i) } for(i in 0 until 3) { print(i) } for(i in 2..8 step 2) { print(i) } for (i in 3 downTo 0) { print(i) } ``` Char ranges are also supported. ```kotlin for (c in 'a'..'d') { print(c) } ``` Ranges are also useful in if statements. ```kotlin if (x in 1..5) { print("x is in range from 1 to 5") } ``` ### While ```kotlin while (condition) { // Code to execute as long as condition is true } ``` ### Do While ```kotlin do { // Code to execute at least once } while (condition) ``` ### Break and Continue ```kotlin for (i in 1..10) { if (i == 5) { break // Exit loop when i is equal to 5 } if (i % 2 == 0) { continue // Skip even numbers and continue to the next iteration } // Code to execute for each odd number between 1 and 10 } ``` ### Exceptions To throw an exception object, use the throw expression: ```kotlin throw Exception("Exception...") ``` To catch an exception, use the try...catch expression: ```kotlin try { // some code } catch (e: SomeException) { // handler } finally { // optional finally block } ``` The Nothing type: This type has no values and is used to mark code locations that can never be reached. In your own code, you can use Nothing to mark a function that never returns. ```kotlin fun fail(message: String): Nothing { throw IllegalArgumentException(message) } ``` ## Functions ### Function Declaration ```kotlin fun sayHello() { println("Hello!") } fun greet(name: String) { println("Hello, $name!") } ``` ### Default arguments and named arguments ```kotlin fun greet(name: String = "World", greeting: String = "Hello") { println("$greeting, $name!") } fun main() { // calling function with default arguments greet() // output: Hello, World! // calling function with named arguments greet(greeting = "Hi", name = "Ali") // output: Hi, Ali! // calling function with some named arguments greet(name = "Reza") // output: Hello, Reza! } ``` ### Function Return Types ```kotlin fun add(a: Int, b: Int): Int { return a + b } fun multiply(a: Int, b: Int) = a * b ``` Unit-returning functions If a function does not return a value, its return type is Unit. ```kotlin fun printHello(): Unit { print("Hello") } ``` Or ```kotlin fun printHello() { print("Hello") } ``` ### Local functions Kotlin supports local functions, which are functions inside other functions. printMessage() is a local function defined within the main() function. ```kotlin fun main() { fun printMessage(message: String) { println("Message: $message") } printMessage("Hello, world!") } ``` ### Member functions A member function is a function that is defined inside a class or object. ```kotlin class Sample { fun foo() {//...} } ``` ### Generic functions Functions can have generic parameters, which are specified using angle brackets before the function name ```kotlin fun function(item: T){ //Code } ``` ### Lambda Expressions ```kotlin val sum = { a: Int, b: Int -> a + b } val square: (Int) -> Int = { it * it } ``` ### Extension Functions and Properties Extension Functions and Properties in Kotlin allow adding new functionality or properties to existing classes without modifying their source code. ```kotlin // Extension function fun String.reverse(): String { return this.reversed() } // Extension property val String.firstChar: Char get() = this[0] ``` ```kotlin fun main() { val str = "Ali" println(str.reverse()) // Prints "ilA" println(str.firstChar) // Prints "A" } ``` ### Higher-Order Functions A higher-order function is a function that takes another function as parameter and/or returns a function. - Taking Functions as Parameters ```kotlin fun calculate(x: Int, y: Int, operation: (Int, Int) -> Int): Int { return operation(x, y) } fun sum(x: Int, y: Int) = x + y ``` ```kotlin fun main() { val sumResult = calculate(1, 7, ::sum) val mulResult = calculate(1, 7) { a, b -> a * b } } ``` - Returning Functions ```kotlin fun operation(): (Int) -> Int { return ::square } fun square(x: Int) = x * x ``` ```kotlin fun main() { val func = operation() println(func(7)) } ``` ### Operator overloading Operator overloading in Kotlin allows you to define and use custom operators for your own classes and types. ```kotlin data class Point(val x: Int, val y: Int) { operator fun plus(other: Point): Point { return Point(x + other.x, y + other.y) } } ``` ```kotlin fun main() { val p1 = Point(1, 2) val p2 = Point(3, 4) val p3 = p1 + p2 // using the overloaded '+' operator println(p3) // Output: Point(x=4, y=6) } ``` ### Variable number of arguments (varargs) Varargs is a feature that allows you to pass a variable number of arguments of the same type to a function ```kotlin fun printNumbers(vararg numbers: Int) { for (number in numbers) { println(number) } } fun main() { printNumbers(1, 2, 3) // prints 1, 2, 3 printNumbers(4, 5, 6, 7, 8) // prints 4, 5, 6, 7, 8 } ``` ### Infix notation Infix in Kotlin allows you to define functions that can be called using infix notation (i.e., without using parentheses and the dot notation). ```kotlin infix fun Int.times(str: String) = str.repeat(this) fun main() { val str = 5 times "Hello " println(str) // Output: "Hello Hello Hello Hello Hello " } ``` ### Scope Functions - let let can be used for scoping and null-checks. When called on an object, let executes the given block of code and returns the result of its last expression. The object is accessible inside the block by the reference it (by default) or a custom name. ```kotlin val message: String? = "Hello" message?.let { print(it.toUpperCase()) // Output: "HELLO" } ``` - run Like let, run is another scoping function from the standard library. Basically, it does the same: executes a code block and returns its result. The difference is that inside run the object is accessed by this. This is useful when you want to call the object's methods rather than pass it as an argument. ```kotlin val message: String? = "Hello" message?.run { print(this.toUpperCase()) // Output: "HELLO" } ``` - with with is a non-extension function that can access members of its argument concisely: you can omit the instance name when referring to its members. ```kotlin val person = Person("Ali", 24) val message = with(person) { "My name is $name and I'm $age years old." } ``` - apply apply executes a block of code on an object and returns the object itself. Inside the block, the object is referenced by this. This function is handy for initializing objects. ```kotlin val person = Person("Ali", 24) person.apply { name = "Ali" age = 24 } ``` - also also works like apply: it executes a given block and returns the object called. Inside the block, the object is referenced by it, so it's easier to pass it as an argument. This function is handy for embedding additional actions, such as logging in call chains. ```kotlin val message: String? = "Hello" message?.also { print(it.toUpperCase()) // Output: "HELLO" } ``` ## Collections ### Array An array is a fixed-size collection of elements of the same data type. - Declaring and Initializing Arrays ```kotlin // Declare an array of integers val numbers = arrayOf(1, 2, 3, 4, 5) // Declare an array of strings val names = arrayOf("Alice", "Bob", "Charlie", "Dave") // Declare an array of a specific size val array = arrayOfNulls(10) // Declare an array of integers with a specified size and initial value val array = Array(7) { i -> i*i } val filledArray = IntArray(5) { index -> index * 2 } // Other type: BooleanArray, ShortArray, DoubleArray and etc. ``` - Accessing Array Elements ```kotlin // Access an element at a specific index val firstNumber = numbers[0] // Access the last element of an array val lastNumber = numbers[numbers.size - 1] ``` - Modifying Array Elements ```kotlin // Modify an element at a specific index numbers[0] = 10 // Fill an array with a specific value Arrays.fill(numbers, 0) ``` - Iterating over Arrays ```kotlin // Iterate over an array using a for loop for (number in numbers) { println(numb ... ...

近期下载者

相关文件


收藏者