Kotlin basic syntax introduction, first from the overall experience of Kotlin programming style.

A statement of the package

Defining packages in Kotlin is a bit different from Java in that there is no need to match directory and package structures, and the source code for Kotlin can be found anywhere on disk.

  • 1. Package declaration

Source files usually start with the package declaration as in Java.

package com.mikyou.hellokotlin

/** * Created by mikyou on 2018/4/1. */
fun main(args: Array<String>) {
    println("Hello Kotlin")}Copy the code
  • 2. Default import of packages

Multiple packages are imported into each Kotlin file by default.

2. Definition of function

  • 1, function definition use keyword “fun”, function parameter format: “parameter: type “, function return value type “fun(…) : Int”
fun sum(a: Int, b: Int, c: Int): Int {
    return a + b + c
}
Copy the code
  • 2, the expression as a function body, the type of the return value can be omitted, you can use Kotlin type derivation function, deduce the type of the return value of the function.
fun sum(a: Int, b: Int, c: Int) = a + b + c
Copy the code
  • 3. A function that returns no value (similar to the void type in Java)
fun printSum(a: Int, b: Int, c: Int): Unit {
	println(a + b + c)
}
Copy the code

Or omit the Unit type

fun printSum(a: Int, b: Int, c: Int) {
	println("sum = ${a + b + c}")}Copy the code
  • Public void setData(Object… Objects).
fun vars(vararg args: Int) {
	for (arg in args) {
		print(arg)
	}
}
Copy the code
  • 5. Lambda (anonymous function)
val sumLambda: (Int.Int.Int) - >Int = { a, b, c -> a + b + c }
Copy the code

test

println("sum = ${sumLambda(1.6.7)}")
Copy the code

Constants and variables

Constants and variables can have no initialized value, but must be initialized before reference. The compiler supports automatic type determination, that is, the declaration can not specify the type, the compiler to determine. The type of the variable must be provided if it is not initialized at declaration time

  • 1, variable variable definition: var keyword

    Var < variable name > : < variable type > = < initial value >

var sum: Int = 3
sum = 8

// The Int type can be omitted because compilation supports type inference
var sum = 3
sum = 8
Copy the code
  • 2, the definition of immutable variables: val keyword, cannot be twice assigned, similar to the Final type in Java

    Val < constant name > : < constant type > = < initial value >

val sum: Int The type must be specified before initialization without assignment
sum = 5
Copy the code
fun sum(a: Int, b: Int, c: Int): Int {
    return a + b + c
}
Copy the code

Four, comments,

Kotlin supports single-line and multi-line comments, similar to Java.

String template

  • 1. Simple names in templates
fun main(args: Array<String>) {
	var a = 1
	var s1 = "a is $a"
}
Copy the code
  • 2. Any expression in the template
fun main(args: Array<String>) {
    var a = 1
    a = 2
    val s2 = "${s1.replace("is", "was")}, but now is $a"
}
Copy the code

Use conditional expressions

  • Replace the trinary operator in Java with an if expression
fun maxOf(a: Int, b: Int): Int {
    if (a > b) {
        return a
    } else {
        return b
    }
}

fun main(args: Array<String>) {
    println(maxOf(1.5))}Copy the code

In Kotlin, if expressions take a return value, so they can be reduced to the following form.

fun maxOf(a: Int, b: Int) = if (a > b) a else b

fun main(args: Array<String>) {
    println(maxOf(1.5))}Copy the code

NULL check mechanism

Kotlin’s empty safety design for the declaration can be empty parameters, in the use of empty judgment processing, there are two processing methods, after the field plus!! Throw an empty exception, as in Java, followed by? Do not do processing return value null or cooperate? : Short judgment processing

// Type after? Indicates nullable
var age: String? = "23"
// field after "!!" Throws a null-pointer exception
valages = age!! .toInt()// add "? "Returns null with no processing
valages1 = age? .toInt()Using "/ /? : "Returns -1 if age is empty
valages2 = age? .toInt() ? :- 1
Copy the code
  • When a reference may be null, the corresponding type declaration must be explicitly marked “? “after the type. “Indicates null. Returns null if the string content in STR is not an integer:
fun main(args: Array<String>) {
    if (args.size < 2) {
        println("Two Integers Expected")
        return
    }
    val x = parseInt(args[0])
    val y = parseInt(args[1])
    
    //println(x + y) may be null, so using x + y is illegal
    if(x ! =null&& y ! =null) {
        println(x + y)
    }
}

fun parseInt(s: String): Int? {// Indicates that the return value of the current function may be null, which must be followed by a "?"
    return s.toInt()
}
Copy the code

Type detection and automatic type conversion

We can use the is operator to detect whether an expression is an instanceof a type (similar to the instanceof keyword in Java).

fun getStringLength(obj: Any): Int? {
    if (obj is String) {
        // Obj is automatically converted to String
        return obj.length
    }

    // There is another method here, unlike Java instanceof, which uses! is
    // if (obj ! is String){
    // // XXX
    // }

    // obj here is still a reference of type Any
    return null
}
Copy the code

or

fun getStringLength(obj: Any): Int? {
  if (obj !is String)
    return null
  // In this branch, the type 'obj' is automatically converted to 'String'
  return obj.length
}
Copy the code

It could even be something like this

fun getStringLength(obj: Any): Int? {
  // On the right side of the && operator, the type of 'obj' is automatically converted to 'String'
  if (obj is String && obj.length > 0)
    return obj.length
  return null
}
Copy the code

Nine, interval

Uses the in operator to check whether a number is within a specified interval. The interval expression has the operator form “..” The rangeTo function assists in and! In. Intervals can support any type that can be compared, and for native integers, there is an optimized implementation inside.

  • 1. Check whether a number is within the specified range
val x = 10
val y = 9
if (x in 1..y + 1) {// Indicates whether x ranges from 1 to y+1.
    println("fits in range")}Copy the code
  • 2. Check whether a number is outside the specified range
val list = listOf("a"."b"."c")
if (- 1 !in 0..list.lastIndex) {
    println("-1 is out of range")}if (list.size !in list.indices) {
    println("list size is out of valid list indices range too")}Copy the code
  • 3. Interval iteration
for(x in 1.10.) {// the equivalent of x >= 1 &&x <= 10
    println(x)
}
Copy the code

or

fun printList(num: Int) {
    for (i in 1..num) {I >= 1 && I <= num
        print(i)
    }
}
Copy the code

Use the until function to exclude the end element

for (i in 1 until 10) {// I in [1, 10] = = 1 &&i < 10
    println(i)
} 
Copy the code
  • 4. Sequence iteration
for(x in 1.100. step 2) {// Incrementing sequence iteration, each interval step is 2; One, three, five, seven...
    println(x)
}

for(x in 9 downTo 0 step 3) {// Decrease the number of iterations, each step is 3; Nine, six, three, zero
    println(x)
}  
Copy the code

10. Use collections

  • 1. Iterate over the collection
fun main(args: Array<String>) {
    val items = list.of("java"."kotlin"."python")
    for (item in items) {
        println(item)
    }
}
Copy the code
  • 2. Use the IN operator to determine whether the collection contains an instance
when {
    "java" in items -> println("is good lang")
    "kotlin" in items -> println("is good good lang")
    else -> println("python is best lang")}Copy the code
  • 3. Use lambda expressions to filter and map collections
fun main(args: Array<String>) {
    val langs = listOf("C"."C++"."Java"."Python"."JavaScript")

    langs.filter { it.startsWith("C") }
            .sortedBy { it }
            .map { it.toUpperCase() }
            .forEach { println(it) }
}
Copy the code

11. Use cycles

There are two ways to loop in Kotlin: for, while, “in” in the for loop, and there are two ways to loop.

  • 1. For loop
val items = listOf("java"."kotlin"."android")
for (item in items) {//for iterates through the collection
    println("lang $item")}for (index in items.indices) {// Similar to the length-index traversal of arrays in Java
    println("The $index index is ${items[index]}")}Copy the code
  • 2. While loop
val items = listOf("java"."kotlin"."android")
var index = 0
while (index < items.size) {// While loop traversal
    println("The $index lang is ${items[index++]}")}Copy the code

If,when,when

The use of if in Kotlin is similar to that in Java, but in Kotin if is an expression that has a value, whereas in Java it is a statement. You can use kotlin if expressions instead of Java trisomes in Kotlin. When functions similarly to switch

fun main(args: Array<String>) {
    println(descript("hello"))}fun descript(obj: Any): String = when (obj) {
    1 -> "one"
    "hello" -> "hello word"
    is Long -> "long type"
    !is String -> "is not String"
    else- > {"unknown type"}}Copy the code

Create classes and instances

fun main(args: Array<String>) {
    val rectangle = Rectangle(100.0.200.0)
    val triangle = Triangle(100.0.100.0.100.0)
    println("rectangle is ${rectangle.isSquare}, and perimeter is ${rectangle.perimeter}, and area is ${rectangle.calculateArea()}")
    println("triangle  perimeter is ${triangle.perimeter}, and area is ${triangle.calculateArea()}")}abstract class Shape(val sides: List<Double>) {
    val perimeter: Double get() = sides.sum()
    abstract fun calculateArea(a): Double
}

interface RectangleProperity {
    val isSquare: Boolean
}

class Rectangle(var height: Double.var length: Double)
    : Shape(listOf(height, length, height, length)), RectangleProperity {
    override fun calculateArea(a): Double = height * length
    override val isSquare: Boolean get() = height == length
}

class Triangle(var sideA: Double.var sideB: Double.var sideC: Double)
    : Shape(listOf(sideA, sideB, sideC)) {
    override fun calculateArea(a): Double = sideA * sideB * sideC
}
Copy the code

This concludes Kotlin’s introduction to basic syntax, and the next article will continue to delve into Kotlin.

Welcome to the Kotlin Developer Association, where the latest Kotlin technical articles are published, and a weekly Kotlin foreign technical article is translated from time to time. If you like Kotlin, welcome to join us ~~~