Kotlin - Introduction Basis

Keywords: Java Android Programming Lambda

Introduction to Kotlin Programming Language

1. Introduction to Kotlin

  • Kotlin is a new JVM-based programming language, which is composed of JetBrains Development
  • Kotlin can be compiled into Java bytecode or JavaScript to run on devices without JVM.
  • JetBrains, as a popular Java IDE IntelliJ Provider, with Apache license, has sourced its Kotlin programming language
  • Kotlin language usage scenarios:

2. Evaluation of Kotlin

1.How to evaluate Kotlin language? - Know
2.How do you think Kotlin has become Google's official support for Android development as a first-level programming language? - Know
3.What advantages does Kotlin have over traditional Java as an Android development language? - Know
4. Personal evaluation

  • Migration: Existing Java code can be converted into Kotlin code with Kotlin plug-in (single, multiple Java files or conversion to the entire project). Although not 100% of the successful conversion can be achieved, but the unsuccessful conversion only needs fine-tuning, OK
  • Interoperability: Mixed development with Java - that's awesome. No one's born with anything, so everyone has a process from exposure to familiarity. Complex Java can be converted into Kotlin in the later stage, giving developers an overlearning, which makes Kotlin gradually penetrate into your project and eventually replace every. java, Kotlin in the project. Similar to the Java language, it's not a big problem for developers to get started in a short time.
  • Learning curve: After using Kotlin, the amount of code in the project is really reduced, and I feel Kotlin is much better than Java 8 (I haven't really understood some new features of Java 8 yet... I don't know why, but I can't look at it after a while, and these days I'm learning Kotlin, but my curiosity explodes...).
  • Tools: Code checking is very strict, to avoid problems after successful compilation, and then go back to the hard debug... After all, some projects are large, each compilation takes time...
  • Comparisons: Without a thorough understanding of other languages, they are not compared with other languages.

3. International Practices - Hello World

//Create a new Hello.kt, write the following contents in the file and run, you can see Hello World! Happy to be out of it.
fun main(args: Array<String>) {
   println("Hello World!")
}

Compared with Java, it feels like the code is much less and more streamlined. (There's still a way to go, and there's still a lot of holes left to go.)

//Java Hello World
public class Hello{
  public static void main(String[] args){
    System.out.println("Hello World!")
  }
}

4. Project Construction

  • Because Kotlin is JetBrains Its own language, so in IntelliJ IDEA can build Kotlin project is of course, IDEA Community version is free, can do Kotlin development.
  • If you are an Android developer, the new Android Studio has integrated the Kotlin plug-in (update or install Kotlin in Plugins if you don't have it). By toolbar - > Code - > Convert Java File to Kotlin FIle, you can convert Java files into Kotlin (remember backup project before conversion, don't play off...)
  • How to build a project is not much to say here. IDEA Download Direct Point Here
  • Following is Kotlin's instructions on the use of several building tools:
    Writing Kotlin Code Documentation
    Using Kapt
    Use Gradle
    Use Maven
    Use Ant
    Kotlin and OSGi
    Compiler plug-in

5. Basic Grammar

After all, Kotlin is the programming language of JVM, so there will be some Kotlin in comparison with Java.

  • Semi-colon ";": Kotlin omits the semicolon at the end of each line of code (;). If you insist on writing, the IDE's syntax check is at most recommended to be deleted, and the code will not be executed because of one more semicolon.
    In the course of my study these days, I always mark the semicolons. When I wrote Demo examples, I had N semicolons on my hands, which were later rejected by me one by one. (My heart refused the semicolons... maybe it was a conditioned reflex.)

  • The basic usage of package is the same as that of import and Java. The basic usage is less than the semicolon at the end of Java.

    • The package name of the package does not have to be the same as the directory name, and it will not be wrong if it is not written, but it is not recommended.
    • If you haven't gone so far and have to go further, I can only tell you that they also have more powerful uses. See the official documents: ChineseEnglish
  • variable and constant

    • val: Like the final state in Java, it can't be modified once it's assigned. It's officially called a Defining local variable, but I think it's only partial when it's defined in a function and invisible to other members. It should be called read-only variable or constant. What's the local ghost?
    val a=1//Automatic inference of `Int'type
    val s="string"//Automatic inference of `String'type
    val temp:String//There is no initial value assigned, so the variable type can not be inferred, so the type can not be omitted!
    temp="fish_leong"
    
    • Variable (var): Like member variables and local variables in Java, they can be redefined and assigned.
      var a=1
      a=2
      var s="string"
      s="123"
    
    • companion object: static variables like those in Java
      //Test.kt
      class Test {
        companion object {
            var Global = "Hello Wordl!"//Add Global attributes to concomitant objects
        }
      }
      //Hello.kt
      fun main(args: Array<String>) {
         println(Test.Global)//Here you can get or modify the Global attribute in Test without instantiating it
         Test.Global="fish_leong"
         println(Test.Global)
      }
    
  • Basic types: Close to Java

    Type Bit width
    Double 64
    Float 32
    Long 64
    Int 32
    Short 16
    Byte 8
    • Type problem: Because of type inference in Kotlin, some beginners will not know what type a variable is, so we can use the following method to save the nation:
      val intRange = 10..21//Integer interval
      println(intRange.javaClass)//class kotlin.ranges.IntRange
      
      val doubleRange = 10.1..20.1//Floating point interval
      println(doubleRange.javaClass)//class kotlin.ranges.ClosedDoubleRange
      
      val str = "fish_leong"//Character string
      println(str.javaClass)//class java.lang.String
      
    • Specific operations on types, such as operations, transformations, can refer to the official basic types of documents: ChineseEnglish
  • Annotations: Basic line-level and block annotations, similar to Java usage, Kotlin Annotation Advancement - Official Documentation: ChineseEnglish

  • Function: Call it Method in Java and define it with fun

    /**
     * Define function
     * Permission modifications: private, protected, internal, public, and open. If no modifier is explicitly specified, the default accessibility is public, as mentioned in Example 8.
     * Parameters: Depending on the actual situation, no, support default parameters
     * Return Value: Types depend on the actual situation, not necessarily, and support type inference of return value
     * Function Body: For simple logic abbreviated, the following will be mentioned
     */
    //Permission modifies fun function name (parameter name: type,...): return value type
    {
      //Function body, there are many ways to write
    }
    
    //Example 1: Functions whose return value is Int
    fun add(x:Int,y:Int):Int{
        return x+y
    }
    
    //Example 2: Functions with return values of Int, which are inferred by type, are simpler than Java to write return and curly brackets.
    fun add1(x: Int, y: Int) = x + y
    
    //Example 3: Function with return value of Int. The return value is inferred by type. If x > y, return x...else...
    fun compare(x: Int, y: Int) = if(x>y) x else y
    
    //Example 4: Functions without return values.
    fun addPrint(x:Int,y:Int):Unit{
      println(x+y)
    }
    
    //Example 5: Unit can omit functions without return values
    fun addPrint1(x:Int,y:Int){
      println(x+y)
    }
    
    //Example 6: Return a function that can be null. Because of Kotlin's empty security mechanism, if the return type String is not added, null cannot be returned.
    fun toCustomString(x: Int, y: Int):String?{
      if(x>y){
          return x.toString()
      }
      return null
    }
    
    /**
     * Example 7: Functions with default parameters
     * Default parameters, which can be called default parameters.
     * The default parameter uses the main rule: you can only omit the last parameter when calling, in other words, if you want to omit a parameter, you must omit all the parameters behind it.
     */
    fun defaultParam(content: String, a: Int = 2, b: Int = 2) {
       println(content + (a + b))
    }
    
    fun main(args: Array<String>) {
        defaultParam("a+b=",1)//Omit the third parameter
        defaultParam("a+b=")//The last two parameters are omitted
        //It is not allowed to omit only the second parameter, because the third parameter is also the default parameter, which does not conform to the rule of using the default parameter.
    }
     
     /**
      * Example 8 Function Modifier
      * New TestA.kt
      * TestA Class, containing five modifier functions
      * private , protected , internal ,public ,open And no modifier. If no modifier is explicitly specified, the default accessibility is public.
      * So public and unmodified are one.
      */
      open class TestA {
          init {
              testPrivate()//private-modified functions, like Java, are visible to members of this class
          }
      
          /**
           * Only functions modified with open can override by subclasses
           * Modified functions are visible to class members, subclass members, and externals
           */
          open fun testOpen() {
              println(this)
          }
      
          /**
           * private Modified functions, like Java, are visible to members of this class
           */
          private fun testPrivate() {
              println(this)
          }
      
          /**
           * protected Modified functions, whose attributes are different from those of private functions, are not visible to the outside world and are accessible to members of subclasses.
           */
          protected fun testProtected() {
              println(this)
          }
      
          /**
           *
           *  Official Interpretation: Any client in this module that can see class declarations can be its internal member
           *  If TestA class is in Modules A and TestB class is in Modules B, then TestB class will not be able to call internal ly modified functions in parent TestA.
           *  The concept of module, a module is a set of Kotlin files compiled together:
           *  An IntelliJ IDEA module;
           *  A Maven project;
           *  A Gradle source set;
           *  A set of files compiled by a < kotlinc > Ant task execution.
           */
          internal fun testInternal() {
              println(this)
          }
      
          /**
           * Without modifiers, it's the same function as public modifiers.
           */
          fun test() {
              println(this)
          }
      }
    
      /**
       * New TestB.kt
       * TestB Class, inherited from TestA class, is not recommended in the same module (Modules) as TestA class, which does not reflect the role of internal ly modified functions.
       */
      class TestB : TestA() {
          /**
           * In override, you can only override functions modified with open in the parent class
           */
          override fun testOpen() {
              super.testOpen()//open-modified functions in parent classes can be overrided by subclasses, external calls, or overrides
    
              test()//It's the same without a modifier as with a public modifier, which can be omitted.
    
              testInternal()//This method is internal ly modified in the parent class TestA. In the same module, the member of the subclass TestB is visible. If TestA and TestB are not in the same module, then the function is invisible to the subclass.
              /**
               * To test the function of the internal modifier, two modules can be built for testing.
               */
      
              testProtected()//You can call the protected-modified function in the parent class, but... see below
              /**
               * protected modified functions can be called by member variables or member functions of parent and parent classes, but not by external calls. Take Chestnut for example:
               * var testA = TestA();
               * testA.testProtected();//In such cases, testProtected is invisible
               */
          }
      }
    

    To understand: Kotlin Air Security

  • String template
    • Traditional string splicing is actually very hard, not only to write a lot of double quotation marks to connect, if a slight misplacement, it will lead to a big mistake! Even String.format() is not as powerful as Kotlin's string template.
    • Kotlin is a string template that allows us to stop pushing.
        val a = "A"
        val b = "B"
        println("a The value is" + a + ",b The value is" + b)//Traditional Writing
        println("a The value is $a,b The value is $b")//Kotlin Replaces Traditional Writing
        println("a The value is ${a.replace("A", "C")},b The value is $b")//Kotlin Writing, Writing Code in Template
      
  • Basic usage of if expressions: Basic usage is similar to Java, but there are some fancy usage in Kotlin
        //Declare a b c, compare a and b, assign a large value to C
      val a = 1
      val b = 2
      var c: Int
      //1. Traditional Writing
      if (a > b) {
          c = a
      } else {
          c = b
      }
      //2.Kotlin Writing, Expressions
      c = if (a > b) a else b
      //3. In Kotlin, the branch of if can be a block of code, and the final expression is the value of the block.
      c = if (a > b) {
          println(a)
          a
      } else {
          println(b)
          b
      }
    
  • Ranges (intervals): In to detect whether a variable is in a specified interval
    See Kotlin Range official documentation for all uses of the interval: ChineseEnglish

      val a = 10
      //The type of 10.100 is IntRange.
      if(a in 10..100){
          println("a At 10-100 Interval")
      }
      //Numbers in cyclic output intervals
      for (s in 1..10) {
          println(s)
      }
    
  • Basic usage of when expressions: similar to switch...case in Java, but Kotlin's when expression seems stronger

    fun testWhen(x: Int) {
      when (x) {
          in 1..10 -> print("x At 1-10 In the interval of")//Interval Judgment
    
          !in 20..21 -> print("x Not in 20-21 In the interval of")//Interval Judgment
    
          is Int -> print("x yes Int type")//Type Judgment
    
          1 -> println(1)//x=1
    
          3 -> {
              println("Sign out")
              System.exit(0)
          }
          else ->//x does not meet other conditions
              println("fish_leong")
      }
    }
    /**
     * when Like if, each branch can be a block of code whose value is the value of the last expression in the block.
     */
    fun testWhen2(x: Int) {
      val c = when (x) {
          1 -> 2
          2 -> 3
          else -> 0
      }
    }
    
  • Basic usage of for loop

      val arrays = arrayOf("1", "2", "3")//Construct an array
      for (element in arrays) {
          println(element)//The loop prints out array elements, similar to for (String str: arrays) {} in Java
      }
      for (pos in arrays.indices) {
          println(arrays[pos])//The array elements are printed out by subscription loops, similar to for (int i=*; i<*; i++) in Java.
      }
    
  • Like do while loops and Java, there's not much to say here.

      var a = 10
      while (a > 0) {
          a--
      }
      a = 10
      do {
          a--
      } while (a > 0)
    
  • Type Detection and Automatic Type Conversion: Kotlin can infer from is whether an expression is a specified type, similar to instanceof in Java, but more powerful than in Java?

    //Any is similar to Object in Java
    fun main(args: Array<String>) {
        val str = "fish_leong"
        val int = 5
        println(getObject(str))
        println(getObject(int))
    }
    fun getObject(obj: Any): Any {
        if (obj is String) {
            //It's not possible to write obj * 3 here, because in this block, obj has been inferred to be String type, so multiplication must not be done.
            return obj.length//Returns string length
        }
        if (obj is Int) {
            return obj * 3//This is inferred as Int type, returning the result of obj*2
        }
        return obj
    }
    
  • Coding specification
    There's nothing to talk about... from Kotlin Language Chinese Station

    • Naming Style
      If you are unsure, default use of Java coding specifications, such as:
      Use hump naming (and avoid naming with underlines)
      Type names begin with capital letters
      Methods and attributes begin with lowercase letters
      Use four space indentations
      Public functions should write function documents so that they appear in Kotlin Doc

    • colon
      There should be a space before the colon between the type and the supertype, and no space before the colon between the instance and the type:
      interface Foo<out T : Any> : Bar { fun foo(a: Int): T}

    • Lambda expression
      In lambda expressions, space should be added around braces, space should be added around arrows separating parameters from code bodies, and lambda expressions should not be written in parentheses as far as possible.

      list.filter { it > 10 }.map { element -> element * 2 }
      

      In non-nested short lambda expressions, it is best to use the default parameter it as a convention
      Instead of explicitly declaring parameter names, in nested parametric lambda expressions, parameters should always be explicitly declared

    • Class header formatting
      Classes with a few parameters can be written in a row:

      class Person(id: Int, name: String)
      

      Classes with long class headers should be formatted so that each primary constructor parameter is in a separate line with indentation. In addition, the right parentheses should be a separate line. If we use inheritance, the list of interfaces invoked or implemented by superclass constructors should be on the same line as parentheses:

      class Person( id: Int, name: String, surname: String) : Human(id, name) { // ......}
      

      For multiple interfaces, superclass constructor calls should be placed first, and then each interface should be in a different row:

      class Person( id: Int, name: String, surname: String) : Human(id, name), KotlinMaker { // ......}
      

      Constructor parameters can be indented by either conventional or continuous indentation (double conventional indentation)

    • Unit
      If the function returns the Unit type, the return type should be omitted:

      fun foo() { // Omitted ": Unit"}
      
    • Function or Attribute

      In many cases, functions without parameters can be interchanged with read-only attributes. Although semantically similar, there are some stylistic conventions of choice.

      The underlying algorithm prefers attributes to functions:

      • No exception will be thrown
      • O(1)
      • Complexity
      • Computing is cheap (or the first run of the cache)
      • Different calls return the same result

There are many other things that have not been mentioned, such as collections, classes and objects, which will be written in future articles. These are the basis of introduction.

[1]Basic Grammar - Kotlin Language Chinese Station
[2]Control flow: if, when, for, while - Kotlin language Chinese station
[3]Coding Specification - Kotlin Language Chinese Station
[4]Module - Kotlin Language Chinese Station
[5]Kotlin-Baidu Encyclopedia
[6]Default parameter - Baidu Encyclopedia

Posted by Anas_M.M.F on Wed, 05 Jun 2019 16:40:14 -0700