The code file usually begins with the declaration of the package: In the above example If no package is specified, the default is Multiple packages are imported into each by default Function definitions use keywords The expression, as the body of the function, returns the automatic inferenceof the type: A function with no return value (similar to The variable length argument of the function can be used with the Variable definition: Immutable variable definition: Both constants and variables can have no initialization value, but must be initialized before referencing The compiler supports automatic type determination, that is, it can be declared without specifying a type, which can be judged by the compiler. Unlike When a reference may be When The following example shows how to use a return value for We can use it. Or It’s even okay. Interval expressions are in the form of operators The interval is defined for any comparable type, but for integer primitive types, it has an optimized implementation. Here are some examples of using intervals: Output result:
Kotlin
file to
.kt
is a suffix. 3.6.1. Package declaration #
package com.runoob.main
import java.util.*
fun test() {}
class Runoob {}
kotlin
source files do not need matching directories and packages, and source files can be placed in any file directory.
test()
, the full name is
com.runoob.main.test
、
Runoob
, the full name is
com.runoob.main.Runoob
.
default
bag. 3.6.2. Default import #
Kotlin
File:
kotlin.*
kotlin.annotation.*
kotlin.collections.*
kotlin.comparisons.*
kotlin.io.*
kotlin.ranges.*
kotlin.sequences.*
kotlin.text.*
3.6.3. Function definition #
fun
, parameter format is: parameter:typefun sum(a: Int, b: Int): Int { // Int parameter, return value Int
return a + b
}
fun sum(a: Int, b: Int) = a + b
public fun sum(a: Int, b: Int): Int = a + b //
The public method must explicitly state the return type
Java
in
void
):fun printSum(a: Int, b: Int): Unit {
print(a + b)
}
// If it returns the Unit type, it can be omitted (also for public methods):
public fun printSum(a: Int, b: Int) {
print(a + b)
}
3.6.4. Variable length parameter function #
vararg
keyword to identify:fun vars(vararg v:Int){
for(vt in v){
print(vt)
}
}
// test
fun main(args: Array<String>) {
vars(1,2,3,4,5) // Output 12345
}
3.6.5. Lambda (anonymous function) #
lambda
examples of expression usage:// test
fun main(args: Array<String>) {
val sumLambda: (Int, Int) -> Int = {x,y -> x+y}
println(sumLambda(1,2)) // Output 3
}
3.6.6. Define constants and variables #
var
keywordVar<identifier>:<type>=<initialization value>
val
keyword, a variable that can only beassigned once (similar to
Java
medium
final
modified variables)Val<identifier>:<type>=<initialization value>
val a: Int = 1
val b = 1 // The system automatically infers
that the variable type is Int
val c: Int // If not initialized at declaration time,
variable type must be provided
c = 1 // definitely assigned
var x = 5 // The system automatically infers that
the variable type is Int
x += 1 // Variable modifiable
3.6.7. Annotation #
Kotlin
single-line and multi-line comments are supported. Examples are as follows:// This is a single line comment
/* This is a multi line block
annotation. */
Java
, block annotations in Kotlin allow nesting.. 3.6.8. String template #
$
represents a variable name or value
$varName
represents the value of a variable
${varName.fun()}
method that represents the variable returns a value:var a = 1
// Simple name in template:
val s1 = "a is $a"
a = 2
// Any expression in the template:
val s2 = "${s1.replace("is", "was")}, but now is $a"
3.6.9. NULL inspection mechanism #
Kotlin
empty security design for parameters that can be declared to be nullable should be processed by null judgment when in use. There are two ways to handle the null security design, adding the field after the field.
!!
like
Java
, the same empty exception is thrown, and another field is added.
?
can not be processed, the return value is
null
or cooperate
?:
with short judgment processing//After the type, add? Indicates that it can be empty
var age: String? = "23"
//Throwing a null pointer exception
val ages = age!!.toInt()
//Returning null without processing
val ages1 = age?.toInt()
//Returning -1 when age is empty
val ages2 = age?.toInt() ?: -1
null
value, the corresponding type declaration must be explicitly marked as
null
.
str
returns when the content of the string in is not an integer
null
:fun parseInt(str: String): Int? {
// ...
}
null
functionof:fun main(args: Array<String>) {
if (args.size < 2) {
print("Two integers expected")
return
}
val x = parseInt(args[0])
val y = parseInt(args[1])
// Directly using 'x * y' can cause errors as they may be null
if (x != null && y != null) {
// After checking for null values, the types of x and y will
be automatically converted to non null variables
print(x * y)
}
}
3.6.10. Type detection and automatic type conversion #
is
operator to detect whether an expression is an instance of a type similar to the one in Java
instanceof
keywords).fun getStringLength(obj: Any): Int? {
if (obj is String) {
// After making type judgments, obj will be automatically converted
to a String type by the system
return obj.length
}
//There is another method here, different from
instanceof in Java, to use is
// if (obj !is String){
// // XXX
// }
// The obj here is still a reference of type Any
return null
}
fun getStringLength(obj: Any): Int? {
if (obj !is String)
return null
// In this branch, the type of `obj` will be
automatically converted to `String`
return obj.length
}
fun getStringLength(obj: Any): Int? {
// On the right side of the `&&` operator, the type of `obj` will be
automatically converted to `String`
if (obj is String && obj.length > 0)
return obj.length
return null
}
3.6.11. Interval #
..
of
rangeTo
function supplemented by
in
and
!in
form.for (i in 1..4) print(i) // Output “1234”
for (i in 4..1) print(i) // Output nothing
if (i in 1..10) { // Equivalent to 1 <= i && i <= 10
println(i)
}
// Use step to specify step size
for (i in 1..4 step 2) print(i) // Output “13”
for (i in 4 downTo 1 step 2) print(i) // Output “42”
// Using the until function to exclude end elements
for (i in 1 until 10) { // i in [1, 10) except 10
println(i)
}
3.6.12. Case test #
fun main(args: Array<String>) {
print("Loop output:")
for (i in 1..4) print(i) // Output “1234”
println("\n----------------")
print("Set Step Size:")
for (i in 1..4 step 2) print(i) // Output “13”
println("\n----------------")
print("use downTo:")
for (i in 4 downTo 1 step 2) print(i) // Output “42”
println("\n----------------")
print("use until:")
// Using the until function to exclude end elements
for (i in 1 until 4) { // i in [1, 4) except 4
print(i)
}
println("\n----------------")
}
Loop output: 1234
----------------
Set step size: 13
----------------
Using downTo: 42
----------------
Use until: 123
----------------