Download Kotlin Docs PDF

TitleKotlin Docs
TagsClass (Computer Programming) Inheritance (Object Oriented Programming) Constructor (Object Oriented Programming) Anonymous Function Method (Computer Programming)
File Size809.5 KB
Total Pages151
Table of Contents
                            Table of Contents
Getting Started
	Basic Syntax
		Defining packages
		Defining functions
		Defining local variables
		Comments
		Using string templates
		Using conditional expressions
		Using nullable values and checking for null
		Using type checks and automatic casts
		Using a for loop
		Using a while loop
		Using when expression
		Using ranges
		Using collections
	Idioms
		Creating DTOs (POJOs/POCOs)
		Default values for function parameters
		Filtering a list
		String Interpolation
		Instance Checks
		Traversing a map/list of pairs
		Using ranges
		Read-only list
		Read-only map
		Accessing a map
		Lazy property
		Extension Functions
		Creating a singleton
		If not null shorthand
		If not null and else shorthand
		Executing a statement if null
		Execute if not null
		Return on when statement
		‘try/catch’ expression
		‘if’ expression
		Builder-style usage of methods that return Unit
		Single-expression functions
		Calling multiple methods on an object instance (‘with’)
		Java 7’s try with resources
		Convenient form for a generic function that requires the generic type information
	Coding Conventions
		Naming Style
		Colon
		Lambdas
		Unit
		Functions vs Properties
Basics
	Basic Types
		Numbers
			Literal Constants
			Representation
			Explicit Conversions
			Operations
		Characters
		Booleans
		Arrays
		Strings
			String Literals
			String Templates
	Packages
		Imports
		Visibility of Top-level Declarations
	Control Flow
		If Expression
		When Expression
		For Loops
		While Loops
		Break and continue in loops
	Returns and Jumps
		Break and Continue Labels
		Return at Labels
Classes and Objects
	Classes and Inheritance
		Classes
			Constructors
			Creating instances of classes
			Class Members
		Inheritance
			Overriding Members
			Overriding Rules
		Abstract Classes
		Companion Objects
		Sealed Classes
	Properties and Fields
		Declaring Properties
		Getters and Setters
			Backing Fields
			Backing Properties
		Compile-Time Constants
		Late-Initialized Properties
		Overriding Properties
		Delegated Properties
	Interfaces
		Implementing Interfaces
		Properties in Interfaces
		Resolving overriding conflicts
	Visibility Modifiers
		Packages
		Classes and Interfaces
			Constructors
			Local declarations
		Modules
	Extensions
		Extension Functions
		Extensions are resolved statically
		Nullable Receiver
		Extension Properties
		Companion Object Extensions
		Scope of Extensions
		Declaring Extensions as Members
		Motivation
	Data Classes
		Copying
		Data Classes and Destructuring Declarations
		Standard Data Classes
	Generics
		Variance
			Declaration-site variance
		Type projections
			Use-site variance: Type projections
			Star-projections
	Generic functions
	Generic constraints
		Upper bounds
	Nested Classes
		Inner classes
	Enum Classes
		Initialization
		Anonymous Classes
		Working with Enum Constants
	Object Expressions and Declarations
		Object expressions
		Object declarations
			Companion Objects
			Semantic difference between object expressions and declarations
	Delegation
		Class Delegation
	Delegated Properties
		Property Delegate Requirements
		Standard Delegates
			Lazy
			Observable
		Storing Properties in a Map
Functions and Lambdas
	Functions
		Function Declarations
		Function Usage
			Infix notation
			Parameters
			Default Arguments
			Named Arguments
			Unit-returning functions
			Single-Expression functions
			Explicit return types
			Variable number of arguments (Varargs)
		Function Scope
			Local Functions
			Member Functions
		Generic Functions
		Inline Functions
		Extension Functions
		Higher-Order Functions and Lambdas
		Tail recursive functions
	Higher-Order Functions and Lambdas
		Higher-Order Functions
		Inline Functions
		Lambda Expressions and Anonymous Functions
			Function Types
			Lambda Expression Syntax
			Anonymous Functions
			Closures
			Function Literals with Receiver
	Inline Functions
		noinline
		Non-local returns
		Reified type parameters
Other
	Destructuring Declarations
		Example: Returning Two Values from a Function
		Example: Destructuring Declarations and Maps
	Collections
	Ranges
		How it works
		Utility functions
			rangeTo()
			downTo()
			reversed()
			step()
	Type Checks and Casts
		is and !is Operators
		Smart Casts
		“Unsafe” cast operator
		“Safe” (nullable) cast operator
	This Expression
		Qualified this
	Equality
		Referential equality
		Structural equality
	Operator overloading
		Conventions
			Unary operations
			Binary operations
		Infix calls for named functions
	Null Safety
		Nullable types and Non-Null Types
		Checking for null in conditions
		Safe Calls
		Elvis Operator
		The !! Operator
		Safe Casts
	Exceptions
		Exception Classes
			Try is an expression
		Checked Exceptions
		Java Interoperability
	Annotations
		Annotation Declaration
			Usage
			Constructors
			Lambdas
		Annotation Use-site Targets
		Java Annotations
	Reflection
		Class References
		Function References
			Example: Function Composition
		Property References
			Interoperability With Java Reflection
		Constructor References
	Type-Safe Builders
		A type-safe builder example
		How it works
		Full definition of the com.example.html package
	Dynamic Type
Reference
Interop
	Calling Java code from Kotlin
		Getters and Setters
		Methods returning void
		Escaping for Java identifiers that are keywords in Kotlin
		Null-Safety and Platform Types
			Notation for Platform Types
			Nullability annotations
		Mapped types
		Java generics in Kotlin
		Java Arrays
		Java Varargs
		Operators
		Checked Exceptions
		Object Methods
			wait()/notify()
			getClass()
			clone()
			finalize()
		Inheritance from Java classes
		Accessing static members
		Java Reflection
		SAM Conversions
		Using JNI with Kotlin
	Calling Kotlin from Java
		Properties
		Package-Level Functions
		Instance Fields
		Static Fields
		Static Methods
		Handling signature clashes with @JvmName
		Overloads Generation
		Checked Exceptions
		Null-safety
		Variant generics
			Translation of type Nothing
Tools
	Documenting Kotlin Code
		Generating the Documentation
		KDoc Syntax
		Block Tags
			@param <name>
			@return
			@constructor
			@property <name>
			@throws <class>, @exception <class>
			@sample <identifier>
			@see <identifier>
			@author
			@since
			@suppress
		Inline Markup
			Linking to Elements
	Using Maven
		Plugin and Versions
		Dependencies
		Compiling Kotlin only source code
		Compiling Kotlin and Java sources
		OSGi
		Examples
	Using Ant
		Getting the Ant Tasks
		Targeting JVM with Kotlin-only source
		Targeting JVM with Kotlin-only source and multiple roots
		Targeting JVM with Kotlin and Java source
		Targeting JavaScript with single source folder
		Targeting JavaScript with Prefix, PostFix and sourcemap options
		Targeting JavaScript with single source folder and metaInfo option
		References
			Attributes common for kotlinc and kotlin2js
			kotlinc Attributes
			kotlin2js Attributes
	Using Gradle
		Plugin and Versions
		Targeting the JVM
		Targeting JavaScript
		Targeting Android
			Android Studio
		Configuring Dependencies
		OSGi
		Examples
	Kotlin and OSGi
		Maven
		Gradle
		FAQ
			Why not just add required manifest options to all Kotlin libraries
FAQ
	FAQ
		Common Questions
			What is Kotlin?
			Why a new language?
			How is it licensed?
			Is it Java Compatible?
			Which minimum Java version is required for running Kotlin code?
			Is there tooling support?
			Is there Eclipse support?
			Is there a standalone compiler?
			Is Kotlin a Functional Language?
			Does Kotlin support generics?
			Are semicolons required?
			Are curly braces required?
			Why have type declarations on the right?
			Will right-handed type declarations affect tooling?
			Is Kotlin extensible?
			Can I embed my DSL into the language?
			What ECMAScript level does the JavaScript support?
			Does the JavaScript back-end support module systems?
	Comparison to Java
		Some Java issues addressed in Kotlin
		What Java has that Kotlin does not
		What Kotlin has that Java does not
	Comparison to Scala
		What Scala has that Kotlin does not
		What Kotlin has that Scala does not
                        
Document Text Contents
Page 1

Kotlin Language Documentation

Page 2

Table of Contents

Getting Started

Basic Syntax

Idioms

Coding Conventions

Basics

Basic Types

Packages

Control Flow

Returns and Jumps

Classes and Objects

Classes and Inheritance

Properties and Fields

Interfaces

Visibility Modifiers

Extensions

Data Classes

Generics

Generic functions

Generic constraints

Nested Classes

Enum Classes

Object Expressions and Declarations

Delegation

Delegated Properties

Functions and Lambdas

Functions

Higher-Order Functions and Lambdas

Inline Functions

Other

4

4

10

15

17

17

23

24

27

29

29

35

39

41

43

49

51

55

55

57

58

60

63

64

67

67

73

78

81

2

Page 75

The parameter less is of type (T, T) -> Boolean , i.e. a function that takes two parameters of type T and returns a

Boolean : true if the first one is smaller than the second one.

In the body, line 4, less is used as a function: it is called by passing two arguments of type T .

A function type is written as above, or may have named parameters, if you want to document the meaning of each parameter.

val compare: (x: T, y: T) -> Int = ...

The full syntactic form of lambda expressions, i.e. literals of function types, is as follows:

val sum = { x: Int, y: Int -> x + y }

A lambda expression is always surrounded by curly braces, parameter declarations in the full syntactic form go inside
parentheses and have optional type annotations, the body goes after an -> sign. If we leave all the optional annotations

out, what’s left looks like this:

val sum: (Int, Int) -> Int = { x, y -> x + y }

It’s very common that a lambda expression has only one parameter. If Kotlin can figure the signature out itself, it allows us
not to declare the only parameter, and will implicitly declare it for us under the name it :

ints.filter { it > 0 } // this literal is of type '(it: Int) -> Boolean'

Note that if a function takes another function as the last parameter, the lambda expression argument can be passed outside
the parenthesized argument list. See the grammar for callSuffix.

One thing missing from the lambda expression syntax presented above is the ability to specify the return type of the function.
In most cases, this is unnecessary because the return type can be inferred automatically. However, if you do need to specify
it explicitly, you can use an alternative syntax: an anonymous function.

fun(x: Int, y: Int): Int = x + y

An anonymous function looks very much like a regular function declaration, except that its name is omitted. Its body can be
either an expression (as shown above) or a block:

fun(x: Int, y: Int): Int {
return x + y
}

The parameters and the return type are specified in the same way as for regular functions, except that the parameter types
can be omitted if they can be inferred from context:

ints.filter(fun(item) = item > 0)

75

Page 76

The return type inference for anonymous functions works just like for normal functions: the return type is inferred
automatically for anonymous functions with an expression body and has to be specified explicitly (or is assumed to be
Unit ) for anonymous functions with a block body.

Note that anonymous function parameters are always passed inside the parentheses. The shorthand syntax allowing to
leave the function outside the parentheses works only for lambda expressions.

One other difference between lambda expressions and anonymous functions is the behavior of non-local returns. A return

statement without a label always returns from the function declared with the fun keyword. This means that a return inside

a lambda expression will return from the enclosing function, whereas a return inside an anonymous function will return

from the anonymous function itself.

A lambda expression or anonymous function (as well as a local function and an object expression) can access its closure,
i.e. the variables declared in the outer scope. Unlike Java, the variables captured in the closure can be modified:

var sum = 0
ints.filter { it > 0 }.forEach {
sum += it
}
print(sum)

Kotlin provides the ability to call a function literal with a specified receiver object. Inside the body of the function literal, you
can call methods on that receiver object without any additional qualifiers. This is similar to extension functions, which allow
you to access members of the receiver object inside the body of the function. One of the most important examples of their
usage is Type-safe Groovy-style builders.

The type of such a function literal is a function type with receiver:

sum : Int.(other: Int) -> Int

The function literal can be called as if it were a method on the receiver object:

1.sum(2)

The anonymous function syntax allows you to specify the receiver type of a function literal directly. This can be useful if you
need to declare a variable of a function type with receiver, and to use it later.

val sum = fun Int.(other: Int): Int = this + other

Lambda expressions can be used as function literals with receiver when the receiver type can be inferred from context.

76

Similer Documents