Simplifying code with Kotlin

Source: Internet
Author: User
Tags foreach gettext tostring advantage
since Google in the IO conference to designate Kotlin as the first level of Android language, Kotlin's popularity is brush brushes up, so, let us look at Kotlin what is the advantage, Google why to use it as the first language of Android? 1.100% compatible Java This is the most important point, because Kotlin is also running on the JVM, and even compiled bytecode files are the same, even directly with the JDK, directly using the Java library, so it seems that Kotlin and Java is 100% compatible. you can call the Kotlin file in Java, or you can use Java files in Kotlin 2. Automatic judgment of type In fact, there is no type, just help you automatically judge, convenient a lot
This is an int.
var a = 1
//This is a string
var b = "string"
//If you want to give them a value, pay attention to the type
a = b//This will be an error.
of course, if you feel uncomfortable, it's fine to give them a type, but that's a lot of extra.
Val A:int = 1
and a smarter one.
If (A is User)
{
    a = B.getuser ()
}
if you write in Java so you can not give the compiler to complain about death, do not give him a mandatory type conversion is certainly not, and in the Kotlin, the compiler is obviously a lot smarter, found that you have judged before, you directly assigned the value of 3. Automatic unboxing This is also filled with Java a pit bar, in the kotlin you no longer need to consider whether it is an int or integer, because in the Kotlin all with int, as to judge all to its own to judge 4. Data Class for those Pojo,kotlin that we often create, we also have grammatical support for them, which is the data class. in the data class encapsulated a lot of things, such as Get/set, ToString, Hashcode and other methods, the definition of Pojo in the future is a lot easier
Data Class User (Val name:string, Val age:int)
Of course, this is still a bit of a pit, because the default class in Kotlin is final, and data default is not empty construction, which caused us to write the program a lot of strange errors but fortunately, the official out of the Noarg and Allopen two plug-ins to help us solve this problem 5. Extension methods in the Kotlin we can give our arbitrary class extension method, take a look at the example to understand
Fun Main (args:array<string>)
{
    println (2.pow2 ())//4.0
} fun

int.pow2 () = Math.pow ( This.todouble (), 2.0)
Here we extend a two-square method to the Int class, and we can even overload the operator
Fun Main (args:array<string>)
{
    val point = Point (2.3,4.5)
    println (-point)  //point (x=-2.3, y=- 4.5)
}

Data class Point (Var x:double, var y:double)
{
    operator fun unaryminus () = Point (-X,-y)
}
6. String concatenation in the Kotlin, the stitching string is no longer the same as before a bunch of plus a spell, it is too tired to see how kotlin is done
Val a = "Hello"
val point = Point (2.3,4.5)
println ("$a, my coordinates are X=${POINT.X},Y=${POINT.Y}")
//Hello, my coordinates are x=2.3, y=4.5
It's not a lot easier. 7. Select Judgment 1. If Expression The if else in Kotlin also has a return value.

Java:

if (a>b) {
   max=a;
   } else{
       max=b;
   }

Kotlin:

Val max = if (a > B) a else B

It's also possible to write.

Val max = if (a > B) {
    println ("a= $a")
       a
   } else {
       println ("b= $b")
       b//default last row is the return value
   }
2. when

Java:

Switch (a)
{case
  1:
    System.out.println (a);
    break;
  Case 2:
    System.out.println (a);
    break;
  Case 3:
    System.out.println (a);
    break;
  Default:
    System.out.println (a);
}

Kotlin:

When (a)
{
  1->println (a)
  1,2->println (a)
  ///can also be so in
  3..33->println (a)
  !in 200..500->println (a)
  //Even so
  Math.max (7,9)->println (a)
  //If you can think of, you can try, whether it is a function or a string, any or anything
  Else->println (a)
}

You can also not judge the condition so that the default judgment Boolean

When
{
  x>10->println (1)
  x<10->println (2)
  Else->print (Ten)
}
7. Lambda expression lambda expressions are used extensively in Kotlin, which makes the code much easier
Where view is it
btn.setonclicklistener {
            val text = It.gettext (). toString ()
            log.i (this, text)
        }
// If not, you can change to this kind of 
btn.setonclicklistener {view-
            val Text = View.gettext (). toString ()
            log.i (this, text)
        }
You can also use:: To refer to a method
Val array = arraylistof<string> ("A", "B", "C")
Array.foreach (::p rintln)
so we can print out all the elements. Here's the most amazing part of Kotlin. 8. Null Security NULL has been dubbed "1 billion dollars of error", but also true, NULL, although useful, but the cause of many errors is often the culprit is his in Kotlin, the compiler is able to recognize that your reference is null, which in turn reminds you. by default, all objects in the Kotlin are not NULL, and if necessary you can add one to the object. This object can be null, but this is not advocated
Data class Hello (var name:string?)
for a Nullable object, you can also use!! To force him not to give an error, but it is advised not to use it unless
Val len = a!!. Length
for forced-type conversions in Java, it becomes a security transformation in Kotlin, and does not report classcastexception when it cannot be transformed, but returns null directly
Val A = b as String
Secure Call (?.)

Java:

int len = null;
if (A! = null)
  len = A.length ();

Kotlin:

var len =a?. Length ()
even this is possible .
Returns null if one is null
d = a?. B?. C?. Length ()
The Elvis operator (?:)

Java:

int Len;
if (A! = null)
  len = A.length ();
else
  len = 0;

Kotlin:

Val len = a?. Length?: 0
9. Operators A lot of operators are built into the Kotlin, which greatly reduces our workload, so let's look at a few ForEach
Val list1 = Listof (1..34, 4..7)
val list2 = listof (2,4,6,23,87)//This has been

mentioned before, many languages have been, can be set to traverse
// The element can be manipulated in conjunction with a lambda expression
List2.foreach {print ("$it")}
List1.foreach {it.foreach {print ("$it")}}
// ForEach does not return a value, so such an operation is actually invalid
list2.foreach{it*2}
Map
Map (Traverse, return list)
val newlist = (1..30). Map {It * 2 + 3}
Newlist.foreach (::p rintln)
FlatMap
FlatMap (Tile multi-collection, return list)
val newList2 = list1.flatmap {It}
Newlist2.foreach (::p rintln)
Reduce
Reduce (traverse and operate on each item and assign the value to ACC to accumulate, the function return value is ACC)
val newList3 = list2.reduce {ACC, I-and I+ACC}
println ( NEWLIST3)
Fold
Fold (reduce with initial value, can also perform string manipulation, etc.)
println (List2.fold (5) {ACC, I-I+ACC})
println (List2.fold ( StringBuffer ()) {ACC, I-acc.append ("$i,")})
Filter and TakeWhile
Filter (filtered when lambda expression returns false)
println (List2.filter {it%2==1})

//takewhile (ends when lambda expression returns false)
println (List2.takewhile {it%2==0})
Let , apply, run
Let (the default current object is it, the return value is the last row)
println (List2.let {
    it.tostring ()
    it[1]
})

//apply ( Within a function you can call the object's method directly, return the object)
println (list2.apply{
    toString ()
    get (1)
})

//run ( You can call the method of the object directly within the function, return the last row)
println (List2.run {
    toString ()
    get (1)
})
you can see that these three function gaps are not big, their greatest use is and? After a non-null judgment, the code is simple to write. Use
Use (the object will be automatically close,try,catch and so on)
BufferedReader (FileReader ("Hello.txt")). Apply {
    var line:string?
    while (true)
    {line
        = It.readline ()?: Break
        println (line)
    }
}
//simplified (ReadText () direct read file)
println (BufferedReader (FileReader ("Hello.txt")). Use {It.readtext ()})
Summary These are not all kotlin, I just take the point that I feel good to say, there are more secrets waiting for you to dig of course, Kotlin now as a new language, there are many shortcomings and immature places, but each new language has just come out of this, and finally rely on everyone's strength and wisdom to solve all of them, the Java just came out so many people do not look good, but the final facts prove everything In General, Kotlin is a collection of the advantages of many languages as one of the language, said the ugly point is the east copy a little bit of the West, and then combined together. But what is this, for a language, set hundred family of the length is very normal thing, as long as the use of the line ——————————————————————————————— I see online about Kotlin and Java a lot of people in the spray, I also want to say a few words. The relationship between Kotlin and Java is related to object C and swift, like an upgrade and a simplified version, but for so many years, we saw that OC no one used, not to mention that Java is more than OC applications, so Java will be eliminated I do not believe, But Kotlin is indeed a trend, after the use of Kotlin must have an advantage Everyone is from Java all the way, to Java has a feeling is normal, but I think this is not a reason to refuse Kotlin, as an IT industry, always look forward should be the most basic bar, not to mention now Google will Kotlin as a first language, Spring5 also to kotlin a lot of support, since everyone is very optimistic about him, we have any reason to refuse it. As for the spray kotlin is a sugar box I do not understand, there is no sugar to eat well. As an object-oriented language, with the language level to give us support is not good, is everyone going to use sinks to write programs. I think in this fast-paced era, can improve productivity of the language is worth promoting, if we always hold the old-fashioned thought, it is probably in this unprecedented pace of development in an era, we will soon be eliminated

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.