In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Most people do not understand the knowledge points of this article "how to configure and use kotlin", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to configure and use kotlin" article.
Kotlin is a static programming language running on the java virtual machine. In 2011, JetBrains launched the kotlin project, and officially released the first official stable version V1.0 on February 15, 2016. in 2017, google officially announced that kotlin has become the official development language of Android at the google I Universe O conference.
Configuration
In our AndroidStudio development tools, to use Kotlin as an excellent development language, we need to install the plug-in, search for Kotlin directly in the install plug-in interface and install it. After that, add the following configuration to the gradle file
Apply plugin:'kotlin-android'apply plugin:'kotlin-android-extensions'dependencies {compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"}
Project gradle file
Buildscript {ext.kotlin_version = '1.1.1' repositories {jcenter ()} dependencies {classpath 'com.android.tools.build:gradle:2.3.1' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" / / NOTE: Do not place your application dependencies here; they belong / / in the individual module build.gradle files}}
After completing the above configuration, we can have a good time.
Kotlin example
First, as before, we create an Android project, automatically create an Activity, and then we create a java class.
Public class MainActivity extends AppCompatActivity {@ Override protected void onCreate (Bundle savedInstanceState) {super.onCreate (savedInstanceState); setContentView (R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById (R.id.toolbar); setSupportActionBar (toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById (R.id.fab) Fab.setOnClickListener (new View.OnClickListener () {@ Override public void onClick (View view) {Snackbar.make (view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction ("Action", null). Show ();}});} @ Override public boolean onCreateOptionsMenu (Menu menu) {/ / Inflate the menu This adds items to the action bar if it is present. GetMenuInflater () .inflate (R.menu.menu_main, menu); return true;} @ Override public boolean onOptionsItemSelected (MenuItem item) {/ / Handle action bar item clicks here. The action bar will / / automatically handle clicks on the Home/Up button, so long / / as you specify a parent activity in AndroidManifest.xml. Int id = item.getItemId (); / / noinspection SimplifiableIfStatement if (id = = R.id.action_settings) {return true;} return super.onOptionsItemSelected (item);}} public class Test {private static String str = null; public static void main (String [] args) {str = "Code4Android"; System.out.println (str);}}
What does the above code look like if it is implemented in kotlin? Although we can't write Kotlin code yet, AS provides the ability to automatically convert Kotlin code after installing the plug-in.
The first knowledge of Kotlin language and the first knowledge of Kotlin language
Converted Kotlin code
Class MainActivity: AppCompatActivity () {override fun onCreate (savedInstanceState: Bundle?) {super.onCreate (savedInstanceState) setContentView (R.layout.activity_main) val toolbar = findViewById (R.id.toolbar) as Toolbar setSupportActionBar (toolbar) val fab = findViewById (R.id.fab) as FloatingActionButton fab.setOnClickListener {view-> Snackbar.make (view, "Replace with your own action" Snackbar.LENGTH_LONG) .setAction ("Action", null) .show ()}} override fun onCreateOptionsMenu (menu: Menu): Boolean {/ / Inflate the menu This adds items to the action bar if it is present. MenuInflater.inflate (R.menu.menu_main, menu) return true} override fun onOptionsItemSelected (item: MenuItem): Boolean {val id = item.itemId if (id = = R.id.action_settings) {return true} return super.onOptionsItemSelected (item)} object Test {private var str: String? = null @ JvmStatic fun main (args: Array) {str = "Code4Android" println (str)}}
Note: AS provides automatic java code conversion function, we do not easily use, let alone transform our mature project, if necessary, we need to ReFactor the implementation ourselves. Otherwise, there will be something unexpected waiting for you, after all, the transformation is not so intelligent. The above code just gives you a brief familiarity with what Kotlin code looks like, and then let's learn the basic syntax of Kotlin. I believe it's easy to get started.
Hello World!
We start with a simple "Hello World!" The output program begins. Similar to the new java file, as shown in the following figure, we choose Kotlin File/Class. Create a Kotlin file.
First know Kotlin language first know Kotlin language package com.learnrecord/***Created by Code4Android on 2017/4/21.*/var str: String = "" fun main (args: Array) {str = "Hello World!" Println (str)}
The above code simply outputs a string "Hello World", followed by the package name, which is different from the java file. The package name does not end with a semicolon ";". In Kotlin syntax, statements no longer end with a semicolon ";".
There are two types of variable declarations in Kotlin. Val decorated variables are read-only variables, that is, they can only be assigned once, and compilation errors will occur when they are assigned again. If we need to modify the value multiple times, we need to use var. In the above var str: String = "", str is the variable name,: String, indicating that the variable is of type String, followed by an assignment statement. We can also write var str= "" omitting the life variable type, which can automatically infer the type based on the assigned value. If we use the following assignment statement str=null, we find that null cannot be assigned. This is the property of Kotlin. If we want to assign null, we can change it to var str:String?= "". Fun is the life of a function, and this main function, like the main method in our java, is the entrance to program execution. Println is a printout.
Kotlin declaration type
There are several Number types in Kotlin, all of which inherit from the Number abstract class.
Float (32-bit), Double (64), Int (32), Byte (8), Short (16), Long (64, type with uppercase L, such as 12L), Any (any type), array type Array automatically matches types based on incoming generic data, and Kotlin also provides Array of a specified type, such as ByteArray,CharArray,ShortArray,IntArray,LongArray,FloatArray,DoubleArray,BooleanArray. The get (index), set (index,value), and iterator () methods are provided in the array types for our use.
Val iArray: IntArray = intArrayOf (1,2,3) val sArray: Array = Array (3, {I-> i.toString ()}) val anyArray: Array = arrayOf (1, "2", 3.0,4.1f) / / types can be mixed into the same array val lArray: LongArray = longArrayOf (1L, 2L, 3L) function
Let's first implement a simple function of numerical summation. The general implementation method is as follows
Fun sum (a: Int, b: Int): Int {return a + b}
Pass in two int values, sum is the name of the function, followed by parentheses: Int indicates that the function returns the value of Int, and the two numbers are added and returned in the function body. Expressions can also be used as function bodies in Kotlin, and the compiler can infer the return type, which can be reduced to
Fun sum (a: Int, b: Int) = a + b
To better understand that an expression can be used as a function body, we can create a function to get the maximum of two numbers, as follows:
Fun max1 (an an else b) = if (a > b) Int
It is important to note that if there are multiple expressions after if, as follows
Fun max1 (aprintln Int) = if (a > b) {println (a) a} else {println (b) / / if we put println (b) below b, the run will return kotlin.Unit as untyped, / / the return value is always the return value or value of the last expression b} println (max1 (1jue 3))
The order of expressions in parentheses determines the value returned and its type.
If our method body is just a print string and does not return a value, then
Fun printInt (a: Int): Unit {println (a)}
Unit is similar to void in our java, that is, there is no return value, so we can omit it.
Fun printInt (a: Int) {println (a)}
There are some modifiers for function bodies, methods, classes, and so on, as well as java, as follows
Abstract / / Abstract class indicates that final / / indicates that the class is not inheritable. The default attribute enum / / indicates that the class enumerates open / / class inheritable, and the class defaults to final's annotation / / annotated class private / / visible only in the same file or subclass, and the unmodifiable class public / / is visible in all calls to internal / / in the same module. If the class does not add a modifier, it defaults to the modifier. The scope is for all modules of the same application, which protects against being called outside the module. Operator
The code is as follows
/ / the left shift operator in Int and Long var a: Int = 4 var shl: Int = a shl (1) / / Java > var ushr: Int = a ushr (3) / / unsigned right under the / / operator Var and: Int = 2 and (4) / / bitwise and operation & var or: Int = 2 or (4) / / bitwise or operation | var xor: Int = 2 xor (6) / / XOR operation ^ print ("/ nshl:" + shl + "/ nshr:" + shr + "/ nushr:" + ushr) print ("/ nand:" + and + "/ nor:" + or + "/ nxor:" + xor)
The output information is
Shl:8shr:2ushr:0and:0or:6xor:4
Some of the operators above can reach the logical operator. When we use Boolean, or () is equivalent to |, and () is equivalent to & &, xor () is true when the two sides of the operator are opposite, otherwise it is false, not ().
Array traversal and control statements
Ergodic array
Fun forLoop (array: Array) {/ / the first way to directly output characters (similar to java foreach) for (str in array) {println (str)} / / Array provides the forEach function array.forEach {println (it)} / / array.indices is the array index for (I in array.indices) { Println (Array [I])} / / (similar to javafor (int iTunes 0) Iwhile (I)
Use when to determine types
Fun whenFun (obj: Any) {when (obj) {25-> println ("25") "Kotlin"-> println ("Kotlin")! is String-> println ("Not String") is Long-> println ("Number is Long") else-> println ("Nothing")}}
In is and java, instanceof is a function to determine whether it is a certain type or not. ! is means to judge that it is not of a certain type.
/ / @ defines label, which is generally used in inner loops to jump to outer loops: I in 0.. 2 is equivalent to for in java (int iLoop 0) Ifor (I in 0.. 2) {for (j in 0.. 3) {println ("I:" + I + "j:" + j) if (j = = 2) / / continue@loop// jump to the outer loop, continue to break@loop / / jump to the outer loop label, jump out of the layer change cycle}}
The reverse output is downTo
/ / output in reverse order 5 4 3 2 10 for (I in 5 downTo 0) {println (I)} / set output data step for (I in 1.. 5 step 3) print (I) / output 14 / / step and downTo mix for (I in 5 downTo 1 step 3) print (I) / / output 52 classes and enumerate / * * constructor: constructor * constructor without modifiers (e.g. private) Constructor can be omitted: * when it is a no-parameter constructor, the entire part of the constructor can also be omitted. The omitted constructor defaults to public * because primary constructor cannot contain any code. So initialize it with the init code block, * you can also use the parameter of the constructor in the initialization code block * / open class People private constructor (var id: String, var name: String) {/ / can initialize the attribute in the class: var customName = name.toUpperCase () / initialize the attribute / / secondary constructor, declare it with the constructor prefix, and you must call primary constructor Use the this keyword constructor (id: String, name: String, age: Int): this (id, name) {println ("constructor")} init {println ("initialization operation, you can use the constructor parameter")} / / need open modification before the subclass can open fun study () {print ("study")} / / the colon before People ":" means inheritance. The class interface is also implemented with a colon class Student (id: String, name: String): People (id, name) {var test: Number = 3 private var name1: String? The method modified by get () {return name1} set (value) {name1 = value} / / override is inheritable by default. If you want not to be inherited, you can modify override fun study () {super.study ()}} with the final keyword.
The data class is used to store data, similar to the POJO class and defined using the data keyword. The compiler generates the following four methods for the data class by default
Equals () hashCode () toString () copy () you can see the simplicity of Kotlin through the data class, we create a Staff class with name,position of type String and generics T (use generics only to contact the following generics in Kotlin) java implementation code: public class StaffJ {private String name; private String position; private T age; public String getName () {return name;} public void setName (String name) {this.name = name } public String getPosition () {return position;} public void setPosition (String position) {this.position = position;} public T getAge () {return age;} public void setAge (T age) {this.age = age;}}
Kotlin data class:
Data class Staff (var name: String, val position: String,var age:T)
By comparison, we can see the advantages, one line of code to achieve, the specific use of
Var staff = Staff ("code4Android", "Android engineer", "22") / / instantiate object
To get an attribute such as the name staff.name, the assignment is staff.name= "code4Android2". Since it is said that it can be assigned, the hands-on partner said why I typed the error, as follows
Staff.position= "front end"
Compiler reported an error. We said earlier that val-modified attributes can only be assigned once, so we can't assign val-modified attributes again here.
Fun main (arg:Array) {var staff = Staff ("code4Android", "Android engineer", "22") / / instantiate the object staff.name= "code4Android2" var staff1=staff.copy () / / you can specify default values when using copy You can specify any one with a comma "," separate var staff2=staff.copy (name= "ccc", position= "kotlin") println ("name:$ {staff2.name} position:$ {staff2.position} age ${staff2.age}") / / staff.position= "Kotiln" / / val cannot assign var anotherStaff= Staff ("code4Android", "Android engineer" again 22) / / instantiate object println ("staff toString (): ${staff.toString ()}") println ("anotherStaff toString (): ${anotherStaff.toString ()}") println ("staff hashCode (): ${staff.hashCode ()}") println ("anotherStaff hashCode (): ${anotherStaff.hashCode ()}") println ("staff is equals another staff? ${staff.equals (anotherStaff)}")}
Character templates are used above, and there are two character template forms in Kotlin, / variable, {}
Var name:String= "Code4Android" println ("my name is $name") println ("my name is ${name}") / * java allows anonymous inner classes; kotlin has a similar concept, called object expression-object expressions*/open class KeyBord {open fun onKeyEvent (code:Int): Unit = Unit} / * * anonymous inner class * * / var key=object: KeyBord () {override open fun onKeyEvent (code:Int): Unit = Unit}
Enumerate
Enum class Color {RED,BLACK,BLUE,GREEN,WHITE} fun display () {var color:Color=Color.BLACK / / conversion specifies name as the enumerated value. If it does not match, it throws the form of IllegalArgumentException Color.valueOf ("BLACK") Color.values () / / already array, and returns the enumerated value println (color.name) / gets the enumerated name println (color.ordinal) / / gets the order in which enumerated values are defined in all enumerated arrays, starting with 0}
Enumerations in Kotlin also support methods.
Extension / * fun receiverType.functionName (params) {* body*} * receiverType: the class name to be extended *. : modifier is * functionName: custom extension function name, * params: custom extension function parameter, can be empty * extension function scope, affected by the visibility modifiers of the function * extension function does not modify the original class, but adds a new function to the object of the extended class. * there is a rule that if the extension function is consistent with the original function of the class, the function of the class itself will be given priority when using the function. * / class Employee (var name: String) {fun print () {println ("Employee")} / / extension function fun Employee.println () {print ("println:Employee name is $name")} / * * can extend an empty object * / fun Any?.toString1 (): String {if (this = = null) return "toString1:null" else {return "toString1" + toString ()}} / * * extended properties * because extended properties do not actually add new members to the class * therefore, it is not possible for an extended property to have a back-end domain variable. Therefore, initializers are not allowed for extended properties. * the behavior of extended properties can only be defined by explicitly given valuing and setting methods, which means that extended attributes can only be declared as val and not as var. If it is forcibly declared as var, even if initialized, * will report an exception error at run, indicating that the property does not have a backend domain variable. * / val Employee.lastName: String get () {return "get:" + name}
Use
Fun main (arg: Array) {var employee = Employee ("Code4Android") employee.print () employee.println () println (employee.toString1 ()) println (employee.lastName)} proxy * proxy interface * / interface Base {fun display ()} / * proxy class * / open class BaseImpl: Base {override fun display () = print ("just display me.")} / * proxy class Use: and the keyword by to declare * allow proxy attributes and other inherited attributes to share * class Drived (base: Base): Base by base BaseImpl () * / class Drived (base: Base): Base by base// uses fun show () {var b = BaseImpl () var drived = Drived (b) drived.display ()} * proxy type: * lazy load: Lazy* Observer: Delegates.observable () * non-empty attribute: Delegates.notNull () * / class Water {public var weight:Int by Delegates.notNull () / * proxy attribute * / public val name: String by lazy {println ("Lazy.") "Code4Android"} public var value: String by Delegates.observable ("init value") {d, old New-> println ("$old- > $new")} fun main (arg: Array) {show () var water = Water () println (water.name) println (water.name) water.value = "11111" water.value = "22222" water.value = "33333" println (water.value) println (water.value) / / must be assigned first otherwise IllegalStateException: Property weight should be initialized before get. Water.weight=2 print (water.weight)} operator:: val String.lastChar: Char get () = this [this.length-1] class A (val p: Int) / / 1, reflected to the runtime class reference: val c = Student::class / / 2, function reference fun isOdd (x: Int) = x% 2! = 0 val numbers = listOf (1,2,3) println (numbers.filter (:: isOdd)) / / 3 Attribute reference (here refers to the variable declared outside the body of the main function) println (:: x.get ()):: x.set (2) println (x) / / 4 the x.set (2) println (x) / / 4 the println expression is evaluated as an attribute of type KProperty / / it allows us to read its value using get () or retrieve its attribute val prop = println p println (prop.get (A (1)) / / 5 by name. For the extended attribute println (String::lastChar.get ("abc")) / / 6, call println (A::p.javaClass) with java reflection, var f: Array = A::p.javaClass.declaredFields accompanying object
Concomitant objects (companion object) are similar to the static keyword static in java. There is no such keyword in Kotlin, but concomitant object.
Open class People constructor (var id: String, var name: String) {/ / can initialize attributes in the class: var customName = name.toUpperCase () / initialize attributes / / declare using the constructor prefix, and must call primary constructor, using the this keyword constructor (id: String, name: String, age: Int): this (id, name) {println ("constructor")} init {println ("initialization operation") You can use the constructor parameter ")} / /, Kotlin's class does not support static variables, so you need to use companion object to declare static variables. / / in fact, this platformStatic variable is not a real static variable, but a concomitant object, companion object {val ID = 1}}.
People.ID directly if you use it.
Singleton mode
When using object to decorate a class in Kotlin. This class is a singleton object.
/ * * object is used to define a class, the instance of this class is a singleton, and the class name is directly used to access the singleton. * it cannot be accessed through the constructor, and it is not allowed to have a constructor * Place.doSomething () / access singleton object * / object Singleton {fun doSomething () {println ("doSomething")}} / * when the singleton is instantiated, the singleton is loaded lazily and loaded only when it is used The object expression is loaded at the initialization point. * * when you use the object keyword to define an object within a class, you are allowed to access its related properties and methods directly through the class name of the external class, which is equivalent to a static variable * you can use companion to modify a singleton, then when you access its properties or methods Allow you to omit the singleton name * MyClass.doSomething () / / access the internal singleton object method * / class MyClass {companion object Singleton {fun doSomething () {println ("doSomething")} above is about how to configure and use kotlin. I believe you all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about it, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.