Learning Kotlin 02

Source: Internet
Author: User
Tags abstract comparable constant constructor numeric json modifier modifiers

All the examples in this article are intended for demonstration purposes only and have no practical meaning, and the code that does not represent the production environment should be written like this. Basic data Types

In Kotlin, everything is objects (everything is an object), including basic data types in Java (primitive types) so that we can call their methods directly or access their properties. Therefore, literals belonging to the base data type in Java can also call their methods directly in Kotlin:

Kotlin
println (1.toString ())   //1
println (1.equals (2))    //False
numeric type (number)

Kotlin numeric data types include the following 6 kinds: Double, Float, Long, Int, Short, Byte, and their lengths are 64, 32, 64, 32, 16, 8, respectively.

Char type does not belong to numeric type

Note that the Char type is not a numeric type in Kotlin. So Java code like this will not compile in Kotlin:

Java
char a = n;
System.out.println (a);  A
Kotlin
val A:char =/    /compile failed because the assignment symbol has inconsistent types on both sides

But Kotlin provides a ToChar method for all numeric types, plus "raw data types can call methods directly," we can also easily achieve the original purpose.

Kotlin
val A = 65.toChar ()
println (65.toChar ())    //A
println (66l.tochar ())   //B
println ( 66.4.toChar ())  //b
println (66.6.toChar ())  //b

No implicit conversions

Kotlin does not automatically promote low-precision numeric types to high-precision numeric types except that the Char type is not part of a numeric type. Common Java code like this will fail to compile in Kotlin.

java
int i = 1;
// ...
Long L = i;
Kotlin
var i:int = 1
//...
var L:long = i     //failed because the Int type is not automatically promoted to a Long type

We need to explicitly tell the compiler that I should be used as a Long type. To facilitate the conversion of data types, all numeric types in Kotlin (subclasses of the number Class) implement the conversion method of the numbers class:

Public abstract class Number {public
    abstract Fun todouble (): Double public
    Abstract Fun tofloat (): Float
    Public abstract Fun Tolong (): Long public
    Abstract Fun ToInt (): Int. Public
    Abstract Fun ToChar (): Char
    Publ IC Abstract Fun Toshort (): Short public
    abstract Fun ToByte (): Byte
}

Even if the Char type is not a subclass of type number, it also provides the same series of conversion functions as the method signature above.

Literal numeric representation method

In Java, there are 3 ways to represent numeric literals, that is, hexadecimal , decimal , and octal , until Java7, which can be used to represent a numeric literal in binary notation.

int eight = 010;              Octal, prefixed with 0
System.out.println (eight);      8
int sixteen = 0x10;               hexadecimal, prefixed with 0x
System.out.println (sixteen);    The
int ten = ten;                 Decimal, nothing special
System.out.println (ten);        Ten
int = 0B10;                   Binary, prefixed with 0b. (since 1.7)
System.out.println (both);      2

Kotlin, however, removed the octal notation, leaving only three other representations, which are consistent with Java and do not repeat. character type (Character)

Character types cannot be used as integers for operation and Operation Boolean (Boolean)

Nothing special Strings (string)

The string in Kotlin is immutable as a string in Java, but because of the other features of Kotlin, the manipulation of strings in Kotlin is much more convenient and plentiful than in Java.

Subscript operation

Since Kotlin opens the door to operator overloading, it is now possible to get the nth character of the string str by str[n], but because the string is indeed immutable, it is not possible to change the nth character of the string Str in any way by using str[n] = ' a ':

Val str = "abc"
println (str[1])
str[1] = ' d '  //compile failed, cannot change string

There are also StringBuilder and stringbuffer that are closely related to strings, but they are mutable, so it is possible to use subscripts to change them:

Val sb = StringBuilder ("ABCD")
sb[0] = ' d '
println (SB)       //DBCD

string literal (literals)

The literal representation of strings in Kotlin, in addition to the most basic representations of Java inheritance, also learns (Chao) the way Python is represented. The notation like Val helloWorld = "Hello \ n World" is indistinguishable with Java, but it may be a bit painful to build a JSON string like the following in Java to test the JSON parsing tool or to store the code in a string.

Private String Getfanslogininfo () {
string returnbody = "{\ n" +
  "\" snsuid\ ": \" fansj\ ", \ n" +
  "\" Snsplatform \ ": \" tw\ ", \ n" +
  "\" nickname\ ": \" groupy\ ", \ n" +
  "\" avatar\ ": \" aa\ ", \ n" +
  "\" sign\ ": \" aa\ ", \ n" +
  "\" Introduce\ ": \" \ "\ n" + "
  }";

return returnbody;
}
public void Printmain () {
System.out.println ("\t\tpublic static void Main (String[]args) {\ n"
  + "\t\t\ tpersonutil.persisted (New Person ()); \ n "+
  " \t\t} ");

Kotlin can use the raw string (raw string) to represent a complex string literal, surrounded by 3 double quotes:

Fun mainmethodinstring (): String {
return ' "" Public
  static void Main (string[] args) {
    personutil.persisted (New Person ());
}
""
}

It is important to note that there is no concept of escape characters in raw string, so such as \n,\t will be output as-is.

String template

The Kotlin string template syntax is very similar to Swift, except that the latter uses \ () to add an expression to a string, and Kotlin uses ${}, which can be omitted when the expression in the curly braces is a simple variable name:

Fun Hello (name:string): String {
return "Hello $name"
}

String templates can also be used in raw string, but raw string does not support \ Escape, so if you want to output $ itself, use ${' $ '}. Arrays (Array)

Kotlin uses array to represent an array, to declare an Int array A, you can use the

var a:array<int>

You can also use

var A:intarray

Avoid the cost of automatically packing and unpacking. To quickly declare and initialize an INT array, you can use the convenient method arrayof (), and also to avoid the cost of packing and unpacking, Kotlin also provides convenient operation of the original data type, var array = intarrayof (1, 2, 3). For 6 data types, Kotlin provides the appropriate method xxxarrayof. Control Flow an If expression

In Kotlin, the IF statement is an expression, which means that the IF statement has a return value. Because the IF statement already provides the function of the three-mesh operator, Kotlin does not have a trinocular operation symbol:

java
int absA = a >= 0? A:-A;
Kotlin
val AbsA = if (a >= 0) a else-a

If the branch can also be a block of code, if it is not too cumbersome, the above code can also be written as:

Kotlin
var absa:int
if (a >= 0) {
AbsA = a
} else {
AbsA =-a
}

If the if branch is a block of code, its last expression is the return value of the branch.

Kotlin
var AbsA = if (a >= 0) {
println ("A is positive")
a
} else {
println ("A is negative") 
  -a
}

Note : When an if is used as an expression (that is, a value is returned in the if and assigned to a variable), an else branch must be provided. When expression

The When statement is used in Kotlin instead of the switch statement in Java, similar to If, when is an expression. The When expression in Kotlin is more powerful than the switch statement functionality in Java (or any other language). The syntax of the when expression is expressed as follows:

When (used by atomicexpression)
  : "When" (("expression") ")?" {"
        whenentry*
    "} "
  ;
Whenentry (used
  by): whencondition{","} "," Controlstructurebody SEMI
  : "Else" "-" Controlstructurebody SEMI
  ;
Whencondition (used by whenentry)
  : Expression
  : (' in ' | "!in") expression
  : ("is" | "!is") type
  ;

Unlike the Java switch statement, which requires that all case must be a constant expression, the case entry in the when expression can be any constant, variable, expression, function call, or type judgment (Is,!is) that is consistent with the when parameter type, and contains the relationship judgment (in,!i N):

Kotlin
Open Class person (open val age:int = 0)
class Employee (override Val age:int = 0, val leader:person?) : Person (age) {Fun work
() {
  println (' working ')
}
}

val person = person (All)
val lisi = Employee ( , person)
val elites = arrayof (Lisi)
val superelites = arrayof (Lisi)
val Zhangsan = Employee (Lisi) 
  val Description = when (Lisi) {
was employee, {
  lisi.work ()
  "a normal employee"
}
in elites, in Supe Relites, "an elite"
Zhangsan.leader, "Zhang San's leader" else--"
Unknown"
}
println (description)  //An ordinary employee

Although there is no explicit break statement, the when expression is returned as long as the when expression has a branch that satisfies the condition in order from the top.

When used as a statement, the return value in its branch code block is equivalent to being ignored (similar to IF):

Kotlin when
{person
= = = Lisi-println ("This is John Doe") person
= = = Zhangsan.leader ("This is the leader of println" )
Zhangsan in elites, println ("Zhang Three is a talent ah")
}

Kotlin = = is equivalent to calling the Equals method, = = = = = = = = In Java, that is, compare reference for loop

The For loop is able to iterate over any object that provides the iterator () function. The syntax structure is defined as follows:

for (used by loop)
  : "For" ("Annotations" (Multiplevariabledeclarations | Variabledeclarationentry) "in" expression ")" Controlstructurebody
  ;

The iteration variables can use annotations, or there can be multiple iteration variables (constituent tuples) that can be conveniently destructure objects on the collection of objects that provide the COMPONENTN function, typically in the case of traversing the Map and traversing the array with the subscript:

Kotlin for
(@NotNull elite in elites) {
println (Elite)
}

val map = mapof (1 to "one", 2 to "a", 3 to "three") for
((key, value) in map) {
println ("$key corresponds to English $value")
} for

((index, value) in Array.with Index ()) {
  println ("The element at $index is $value")
}
While Loop

Nothing special function

In Kotlin, declaring a function using the fun keyword is pun. The syntax rules for declaring a function are as follows:

function (used by memberdeclaration, Declaration, Toplevelobject)
  : Modifiers ' fun '
      typeparameters?
      (type ".")?
      Simplename
      typeparameters? Valueparameters (":" type)?
      Typeconstraints
      functionbody?
  ;
Functionbody (used by getter, setter, function)
  : block
  : "=" expression
  ;

The first is the modifiers modifier, as in Java, the Kotlin function has public, protected, private access modifiers and abstract, final modifiers

And then the keyword fun.

Then the generic parameter, which can be used when declaring a generic method:

Fun <T:Comparable<T>> Max (N1:t, n2:t): T {
return if (N1 > N2) N1 else N2
}

The method name is followed by the optional type in front of the method name. , when you use Kotlin to add a method to an existing class, you need to specify which class the method is added to, such as we want to add a localized method to the String class localized, we need to specify the type to indicate that the method is added to the string:

Fun string.localized (): String {
return if (this = = "Hello") "Hello" else "do not understand"
}

followed by the function arguments, the Kotlin parameter declaration uses Pascal's notation, namely Name:type, which separates multiple parameters with commas.

Next is the type constraint, which has additional constraints when declaring a generic function that can be specified with a WHERE statement

Ultimately the function body, the function body can be a code block, when the function body only one row, directly with =:

Fun <T:Comparable<T>> Max (A:t, b:t): T = if (a > B) a else B

infix function (infix)

As the name implies, the infix function refers to a function that can be called in the form of an infix expression like a plus B when calling a function. Because of the existence of the Kotlin infix function, many seemingly ordinary function calls look like magic. To be able to invoke a function in infix form, the following conditions must be met: a member function or a extension function with only one argument decorated with the infix modifier

From the Kotlin class library to find a few infix functions as a reference:

Public infix Fun SHL (bitcount:int): int  //left shift operation, 1 SHL 2 = 4 public
infix fun shr (bitcount:int): int  //Right Shift  Operation, 4 SHR 2 = 1 public
infix fun ushr (bitcount:int): Int//Unsigned Right SHIFT, 4 ushr 2 = 1073741823 public
infix fun <a, B> a.to (that:b): pair<a, b> = Pair (this, that)

The last function is to quickly create a two-tuple infix function, which is called 1 to "one", because of this convenient creation, Kotlin provides a quick way to create a map function is also very convenient and concise:

Class Modelandview (viewname:string, model:map<string, any?>) Fun

index (): Modelandview {
   //...
   Return Modelandview ("index", Mapof ("name" to "Kid", "age" to))
}
parameter default value/named parameter

The parameters in the Kotlin function can have a default value, and after the parameter declaration, use = <default> to specify the default value of <default> for the parameter:

Fun SayHello (name:string = "World", Times:int = 1) {
    repeat (times) {
        println ("Hello $name")
    }
}
  sayhello ()  //Hello World

When you call a function, you can not pass parameters for parameters that already have a default value specified. You do not have to pass parameters in the order in which they are declared, but you must specify the name of the parameter to pass (the parameter is named for the function), and with this feature you can reduce the number of overloaded functions, such as the above function SayHello can be called as follows:

SayHello (times = 2, name = "Kid")
SayHello (times = 2)
SayHello (name = "Kid")

We use this attribute in the JavaBean constructor:

Open Class Person (var id:int = null, var name:string? = null, var age:int? = null)

val p1 = person (id = 1)
val P2 = person (name = "Kid", age = All)
val p3 = person (id = 2, age = 23)

If you use Java to implement the same constructor, for a class with three fields, provide (3 + 6 + 6) = 15 constructors (if the argument type does not conflict). Unit return value

Kotlin, when the return value of a declared method is a unit, it indicates that the method returns a unit (nothing is returned). The Unit is similar to void in Java. For a function that returns a unit, its return type can be unspecified, and its function body does not need to return the unit explicitly, so the following functions are equivalent:

Kotlin

//explicitly specify Fun
a (): unit {
    return unit
}

//Do not specify return type fun
B () {
    return unit
}< c14/>//does not explicitly return fun
C (): Unit {
}
higher order functions and lambda

Higher-order functions are functions that accept functions as parameters or return functions as return values.

The official web site provides a more complex example detailing the high-order function stamp here, borrowing from another simple example of learning swift that is often cited as introducing Kotlin's higher-order functions for comparison.

To implement a function adder receive a numeric parameter a, and then return a new function, the new function receives a numeric parameter that returns the value after the argument plus a. For example:

Val Addten = Adder (Ten)  //Addten is a function
println (addten)     //
val AddTwo = Adder (2)
println ( AddTwo (Ten))     //12
function as return value

In Kotlin, when a function is used as an argument or a return value, its type is different from the following when declaring a function: Do not need the fun keyword and the function Name argument list and the return value between: use, replace

For example, when declaring a addTwo function directly, this is the case:

Fun AddTwo (n:int): Int {return n + 2}

If you want to use a function that has the same signature as the function as a parameter or return value:

((N:int), Int)

so the above function of building adder can be implemented as follows:

Kotlin Fun
Adder (n:int): ((a:int)-int) {  //return value is this type of function: ((a:int)-int) 
  return Fun (a:int): I NT {        //returns the function, where the function is written in the same way as the normal notation
    return a + N
  }
}
function as a parameter

If the above example, we passed the parameter a also want to be passed in a function to calculate, then the original parameter A will need to use a function as a parameter:

Kotlin Fun
Adder (afun: () int): ((a:int)-int) {
  return Fun (a:int): int {
    return a + afun () c11/>}
}

You need to pass in a function as a parameter when calling:

Kotlin
val tenfun = Fun (): Int {return ten}
val Addten = Adder (tenfun)
println (Addten (10))
Lambda

It's a little cumbersome to call a function that has a function as a parameter, because you first create a function, assign a value to Tenfun, and then pass the variable to the function adder, even if the argument function you want to pass simply returns 10. In Kotlin, when a lambda expression can be passed as a parameter to a transfer function, the lambda expression has the following characteristics: Always use {} to enclose if the lambda has parameters, then write the contents of the lambda before the The lambda parameter type can be omitted (can be inferred)

Use lambda for the transfer function in the example above:

Kotlin
val Addten = Adder ({10})

Because the lambda has no parameters, it can be omitted:

If the lambda expression has only one parameter, the parameter can also be omitted, and it can be referenced to that parameter within the lambda.

Kotlin
val Addten = Adder ({10})

When the lambda expression is the last parameter of a function, the lambda expression can be referred to outside the parentheses:

Kotlin
val addten = Adder () {10}

If the lambda expression is also the only argument to a function, the () function call can also be omitted:

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.