Swift, Kotlin:android World

Source: Internet
Author: User
Tags types of functions

This digest is from Infoq original address: Http://www.infoq.com/cn/news/2015/06/Android-JVM-JetBrains-Kotlin

Kotlin is a static-type JVM language similar to Swift, developed and open source by JetBrains design. Compared to Java, Kotlin's syntax is more concise, more expressive, and offers more features, such as higher-order functions, operator overloading, and string templates. It is highly interoperable with Java and can be used in one project at a time.

According to JetBrains, based on their years of experience in Java platform Development, they believe that the Java programming language has some limitations and problems, and because of the need for backward compatibility, they are impossible or difficult to solve. As a result, they created the Kotlin project, with the main objectives being:

    • Create a Java-compatible language
    • Compile at least as fast as Java
    • More secure than Java
    • More Concise than Java
    • is simpler than the most mature competitor Scala

Ashraff Hathibelagal is an independent developer who likes to study new frameworks and SDKs. Recently, he wrote about some of Kotlin's grammar. According to him, a qualified Java programmer can learn to use Kotlin in a very short period of time.

Classes and constructors

Kotlin creates a class in a similar way to Java, such as the following code that creates a class with three attributes Person :

class Person{    var name: String = ""    var age: Int = 0    var college: String? = null}

As you can see, Kotlin's variable declarations are slightly different. In Kotline, declaring a variable must use a keyword var , and if you want to create a read-only/assignment-only variable, you need to use val it instead. In addition, in order to implement "null safety", Kotlin can distinguish between nullable variables and non-nullable variables. In the preceding code, variables name and age non-nullable arguments college can be null. Once the class is defined, it is very simple to create an instance:

var jake = Person()

Note that Kotlin does not have a keyword new . Once the instance is created, you can assign a value to the variable as in Java:

jake.name = "Jake Hill"jake.age = 24jake.college = "Stephen‘s College"

Variables can be assigned in these ways, or they can be assigned by constructors, but the latter is a better coding practice. In Kotlin, creating such a constructor is simple:

class Person(var name: String, var age: Int, var college: String?) {}

In fact, because there are no other operations in the constructor, the curly braces can be omitted, and the code becomes quite concise:

class Person(var name: String, var age: Int, var college: String?)var jake = Person("Jake Hill", 24, "Stephen‘s College")

The constructors in the preceding code are part of the class header, called the primary constructor. In Kotlin, you can also use constructor keywords to create auxiliary constructors, for example, the following code adds an auxiliary constructor to initialize the variable email :

class Person(var name: String, var age: Int, var college: String?) {    var email: String = ""    constructor(name:String, age:Int, college: String?, email: String) : this(name, age, college) {        this.email = email    }}

Kotlin allows you to create derived classes, but follow these rules:

    • You must use a keyword in place of Java extends
    • The base class header must have open annotations
    • The base class must have a constructor with parameters, and the derived class will initialize those parameters in its own header

For example, the following code creates a Empoyee derived class named:

open class Person(var name: String, var age: Int, var college: String?) {    ...}class Employee(name: String, age: Int, college: String?, var company: String) : Person(name, age, college) {}

Functions and extensions

There are overloads that have derivations. Like derivation of a class, methods that allow overloading are open annotated, and annotations are used when overloaded in derived classes override . For example, here is the code for a Employee Person method that overloads a class in a class isEligibleToVote :

override fun isEligibleToVote(): Boolean {    return true}

In addition to changing the existing behavior of the class, Kotlin also allows the developer to implement extensions to the class without modifying the original definition of the class, as the following code Person adds a name extension to isTeenager the class:

fun Person.isTeenager(): Boolean {    return age in 13..19}

This feature is especially useful when you need to extend a class from another project.

The functions mentioned above are similar to functions in Java, but Kotlin also supports other types of functions. If a function returns the value of a single expression, you can use it = to define the function. Here is an example of creating a single-expression function:

fun isOctogenarian(): Boolean = age in 80 .. 89

Kotlin also supports higher-order functions and lambda expressions. For example, a lambda expression {x,y->x+y} can assign a value to a variable as follows:

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

The following higher order function takes the above expression as a parameter and doubles the result of the expression:

fun doubleTheResult(x:Int, y:Int, f:(Int, Int)->Int): Int {    return f(x,y) * 2}

The function can be called using one of the following methods:

val result1 = doubleTheResult(3, 4, sumLambda)

Or

val result2 = doubleTheResult(3, 4, {x,y -> x+y})

Range expression

In Kotlin, range expressions are used more. Scope creation requires only .. operators, for example:

val r1 = 1..5//该范围包含数值1,2,3,4,5

If you create a descending range, you need to use downTo functions such as:

val r2 = 5 downTo 1//该范围包含数值5,4,3,2,1

If the step is not 1, you need to use step a function, for example:

val r3 = 5 downTo 1 step 2//该范围包含数值5,3,1

Conditional structure

In Kotlin, if is an expression that returns different values depending on whether the condition satisfies, for example, the following code is isEligibleToVote set to "Yes"

var age = 20val isEligibleToVote = if(age > 18) "Yes" else "No"

whenThe expression is equivalent to Java, switch but more powerful, for example, the following code will be typeOfPerson set to "teenager":

val age = 17val typeOfPerson = when(age){    0 -> "New born"    in 1..12 -> "Child"    in 13..19 -> "Teenager"    else -> "Adult"}

Loop structure

Kotlin uses for..in traversal arrays, collections, and other data structures that provide iterators, which are almost identical to Java, except that operators are in replaced by operators : , for example, the following code iterates over an String array of objects:

val names = arrayOf("Jake", "Jill", "Ashley", "Bill")for (name in names) {    println(name)}

whileand do..while The syntax of the loop is exactly the same as Java.

String templates

Kotlin allows you to embed variables and expressions in strings, such as:

val name = "Bob"println("My name is ${name}") //打印"My name is Bob"val a = 10val b = 20println("The sum is ${a+b}") //打印"The sum is 30"

In addition, Kotlin is highly interoperable with Java. Kotlin can invoke existing Java code in a natural way, and Java makes it easy to invoke the Kotlin code. At the same time, Kotlin can interoperate with JavaScript.

Here are just a few of the basic syntax and features of Kotlin, please refer to the official documentation for more details. In fact, so far, Kotlin is still only a preview version, and in the next few months there will be a number of significant improvements and new features. However, there are more than 400 libraries associated with Kotlin projects on GitHub.

In another article, Hathibelagal writes, "If you're looking for an alternative programming language for Android, you should try Kotlin." It's easy to replace Java in an Android project or use it with Java. Readers who want to learn how to use Kotlin to develop Android projects in Android Studio can read this post.

Swift, Kotlin:android World

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.