当前位置:网站首页>Explanation and use of kotlin syntax for Android
Explanation and use of kotlin syntax for Android
2022-06-25 11:02:00 【Running snail, Z】
background :kotlin
kotlin In today's Android The market has captured a share of the development language , Large companies have been involved in the interview or project kotlin, Now I'll give you a brief introduction kotlin How to avoid the "pit" and how to write it . This document is constantly updated and optimized , The following will be a transition from general to detailed . as well as kotlin The in Android The writing and using skills in !
kotlin Where there is some confusion, the grammar uses
var And val:var Is to define a variable ,var a:Int=1, Can be used later ,val Is to define a constant , It cannot be modified later .
identification :"?" 、"!!"
people?
people?.name?:"name is null"
people!!.name
Switch And when
Three mesh operation A=a>b?c:d,A=if(a>b)c else d
interface A{
public void log();
public void print(String msg);
}
interface A{
public void log();
public void print(msg:String){
println(msh)
}
}
open:
class A constraction(title:String){
var a;
set(){
// modify set Parameters
}
get(){
}
init(){
// Initialization module
}
}
in and is
in: It's traversing numbers , similar java foreach Medium ":"
kotlin:in
for( temp in arry){
}
Java: ":"
for(String value: arry){
}
is: It is the judgment of type , similar java instanceof,
kotlin: if(a is String)
java: if(a instanceof String)
Three mesh operation
kotlin The syntax of does not support ternary operations , because ? stay kotlin Special usage in , If a parameter a?, Indicates if the parameter is null, Will return a null value .
Java: a>b?a:b
kotline: var max=if(a>b) a else b;
Class method 、 Function extension extension :
kotline Support dynamic method extension , There is no need to define a class in advance ,
class MyInfo{
}
// Give... Somewhere else MyInfo Add a new method , You can use the class name +“.”+ Method name
fun MyInfo.getName():String{
return "li si"
}
So you can use
var info:MyInfo=MyInfo()
println(info.getName())
println(MyInfo().getName())
Simple interest :kotlin Simple use keywords for object To decorate
object + Class name
object DateUtil{ var name="nihao" fun get():String{ return name; } }
About class inheritance :
JAVA:extends
kotline: ":"
kotlin The parent class needs to be passed through open To modify , And the inheritance passed ":"+ Class name +()
If class A{
}
open class B{
}
If A Class needs to inherit B class , First, through open Keyword to decorate , Then inherit
class A:B(){
}
Constructor of class :
stay kotlin in , If the parameter needs to be initialized , You need to pass in parameters through class communication , You need to use keywords "constructor" To claim
class A constructor(a :Int,b:Int){
init{
print("a=$a,b=$b")
}
}
The above constructor belongs to the primary constructor , If it is aimed at Java Method overload in , As long as the parameters are different , however kotlin The constructor of has only one master , So you want constructors with different parameters , This can only be done through the secondary constructor .
open class MyConstraction constructor(name: String) { // Rewrite the constructor constructor(name: String, age: Int) { } // Rewrite the constructor constructor(name: String, age: Int, sex: Boolean) { } }
Secondary constructors can be misleading , as well as init Method will be called many times , Therefore, the secondary constructor can also be changed into a primary constructor
open class MyConstraction { constructor(name: String) { } constructor(name: String, age: Int) { } constructor(name: String, age: Int, sex: Boolean) { } }
You can also use the default parameter constructor : You only need to add parameters after the class , No need to pass constructor keyword
open class MyConstraction (msg:String){ constructor(name: String, age: Int) { } constructor(name: String, age: Int, sex: Boolean) { } }
If in Java The default parameter class... Is referenced in the file .new An object , Found an error , Should use the @JvmOverloads Remodel
open claa A @JvmOverloads constructor(name: String, age: Int){
}
Default parameter initial value :
fun ok(msg:String="default"): String {
return msg
}
Variable parameters :vararg
stay Java in , Variable parameters are passed through ... To define , And placed in the last bit of the parameter ,
public void test(String... list);
stay Kotlin in , Variable parameters need to be declared by a keyword :vararg
fun test(vararg arry:String){
}
Array :
Java Defining arrays in int[] arry=new int[2]{1,2};
var intarry:IntArray= intArrayOf(1,2,3,4,5)
Format : Define a variable name : An array type = assignment
String Array :
String A prime group is a little different from other arrays , The data format is as follows
var string_arry:Array<String>=arratOf("A","B","C")
But there may be problems in some versions : Prompt error
Correct as follows :
The first one is :var string_arry=arrayOf("A","B","C",1,2,3,c)
perhaps
The second kind
var string_arry:Array<String>
string_arry=arratOf("A","B","C")
The first way to write it , The contents can be of any type , The second is because var The defined type is String, So the assignment can only be String type , Otherwise, an error will be reported , Because the generic has specified String Lead to .
Character splicing :
stay java in , Character splicing is common as follows
String a="ABC",b="abc";
b=b+c; The result is b="ABCabc",
perhaps StringBuild sb=new StringBuild();
sb.append("ABC").append("abc");
stay kotlin in :
var a="ABC" var b="abc is$a"
The connection is through the dollar sign $ To link the content you want to splice . Unwanted + Number
System.err.println(" String length ${a.length}" )
If the stitching is designed to object properties , Need to pass through {} Wrap it up
Because dollar sign is a special character , Print the symbol as follows :${'$'} perhaps "\$"
Containers :
stay Java in , Containers are common to us map,set etc. , stay kotline There are , however kotlin Can be easily divided into variable sets and read-only sets
Java in : Let's define a set,
Set set=new Set();
set.add(1);
set.add(2);
set.add(3);
At this time ,set There are three values in :1,2,3
stay kotlin in ,
var set:Set<String>
set=setOf(1,2,3,4);
At this time set There are four values in , If you need to add new elements , Through the following plus() Method
set.plus(5), You print and find that it is not synchronized to set In the container , Because plus() Source code is as follows
public operator fun <T> Set<T>.plus(element: T): Set<T> { val result = LinkedHashSet<T>(mapCapacity(size + 1)) result.addAll(this) result.add(element) return result }
After the new value-added , Will generate a new result, This result And the original set Is no longer an object , And in plus The call returns , If you want to be consistent , You only need to assign the result to the current value for each call set, If :
set=set.plus(5), Now ,set Inside is 5 A data set
Variable set :
MutableSet: yes set Can be changed . One more. add Method
therefore var mset:MutableSet<String>=mutableSetOf("A","B","C")
mset.add("D")
Immutable passage plus Can also implement a temporary new variable ,MutableSet Change one more add
List and MutableList It's also a reference Set Usage of . meanwhile , The container itself supports sorting :
sortBy and sortByDescending
Map Use :
java in ,map Provides key and value,
kotline How to write it :
var map:Map<String,String> // The first one is map= mapOf("a" to "65","b" to "66","c" to "67" ); // map= mapOf(Pair("A","96"),Pair("B","97"),Pair("C","99")) If it's variable MutableMap, It can still pass add To add new , If not , Only through plus() To manage
Iteration of the container :
1.in Use
stay Java in , We iteratively use for quite a lot
for(int a=0;a<list.size();a++) perhaps for(String item:list)
But in kotlin in , Use in To deal with it
for(item in list), Also support java Writing
for (index in list.indices) { println( list.get(index)) }
2.Iterator
Java and kotlin All support Iterator, The writing method is basically the same
Java:
Iterator iterator = list.iterator(); while (iterator.hasNext()) { String item=iterator.next(); }
Kotlin:
val iterator=set.iterator(); while (iterator.hasNext()) { var value=iterator.next(); }
3.forEach, As long as for Define a temporary object of container type in the loop
Java Medium forEach:
for(String item:list)
kotlin: The container itself provides a forEach Method ,item For internal it object , Just quote directly
set.forEach { print(it)}
remarks : If you use $it Connector , We need to pay attention to , The connector is a connection "$it", Undefined objects cannot be contiguously followed ,
such as :print(" The value is :$it The number of "), This will give you an error
correct :print(" The value is :$it The number of ") perhaps print(" The value is :${it} The number of ")
Need to pass through {}, Reference the defined variable to the specified location
Conditional statements
1.if Use
kotlin Of if sentence , It can not only be used as a conditional judgment , It can also be used as a trinocular operation
similar Java The binocular operation of , because kotlin Ternary operation is not supported
var resullt=if(3>2){"3>2"}else{"3<2"}
The other is normal conditional judgment :
if(3>2){
printf("3>2");
}else{
printf("3<2");
}
2.when The sentence of
when Statement and Java Medium Switch The sentence is the same , however when Statement supports more conditions than Switch more
Java:
switch (2) { case 1: break; }
kotlin:
when (text) { 1 -> { println("1") } 2 -> { println("2") } 3 -> { println("3") } else -> { println("defaule:") } }
java It's from case, however kotlin Unwanted , direct "text->" Format , If it doesn't hit ,java yes default,kotlin yes else
3.for loop in High order usage of
kotlin for Cyclic non java Of for(int index0;index<size;index++)
kotlin for Characteristics are as follows :
3.1 until, from A To B, But not including B,【10,100), On the left is the closed interval , On the right is the open section
for(item in 0 until 100)
tem=[0,100)
3.2 step: Step size means , similar java for(a;,b;c) in c Conditions
for(temp 0..100 temp 4)
Inside ".." Connect ,0..100=[0,100],step It's the step length
until Can also cooperate temp Use it together :for(item in 0 until 100 temp 4)
3.3downTo: Decreasing means
for ( item in 10 downTo 0) Descending from high to low , similar --
remarks : If the features are not specifically written temp Value , The default step size is 1,
in other words :for ( item in 10 downTo 0)=for ( item in 10 downTo 0 temp 1)
4.while Circulation and do/while Use :
Java and kotlin Is the same usage , You can refer to java,
5. Jump out of multiple loops break and continue And marker bit @.
The basic usage of these two kinds and java equally , however kotlin One more marker bit , Can pass @ To mark the beginning of the loop body , Jump directly to this position
var index: Int = 0 [email protected] while (index < 10) { var j = 0 [email protected] while (j < 10) { if (j == 5) { [email protected] } print("index=${index},j=${j}\n") j++ } index++ }
ad locum , We define two tags :flag and secend, Nest in the second layer while loop break To secend, That is to say if j==5, Jump out of the loop , So let's keep going , If break @flag,j==5, Out of the loop . This is a break usage
continue You can also use the tag , But notice ,continue Using tags may lead to dead cycles , So if you put the top break Switch to continue,
var index: Int = 0 [email protected] while (index < 10) { var j = 0 [email protected] while (j < 10) { if (j == 5) { [email protected] } print("index=${index},j=${j}\n") j++ } index++ }
that , When j=5 when , because j++ stay continue below ,continue Jump to secend Marker bit , such j==5 It hasn't changed , This leads to a dead cycle . So I'm putting continue Combined with marker bit , Be careful
6. Valid determination of string
isNullOrEmpty: Is a null pointer or the string length is 0 return true
isNullOrBlank: Null pointer 、 String length is 0 Or the authoritative space returns true
isEmpty: String length is 0
isBlank: String length is 0 Or all spaces
isNotEmpty: String length greater than 0
isNotBlank: String navigation is greater than 0 It is not all blank space
7. Avoidance and use of empty objects
var a:string?=null
Express a for null, Even if you are using direct return null , No null pointer is reported
The same is true for including method parameters fun test(txt:String?), Express txt for null, otherwise ied It will give you an error
That is, add... After the parameter ?:a?.length return null
7.1 Many times we don't want to null, Want default values , Can pass "?:" To avoid
(a?.length?:0)-> If a by null, So what's back is null, At this time , adopt ?: To achieve the return of the trinocular operator 0
a? The advantage of this writing method is that no null pointer will be thrown , But it will return null
7.2 "!!" Operator , Is the variable from controllable to non nullable , But if the object is null, You need to judge for yourself , Otherwise, null pointer will be reported
var people:People?=null people=People() println(people.name?:"")// Returns an empty println(people.name)// return null
8.== and equals Comparison of ,“===” What is it again? ?
println("a"=="a") true println("a".equals("a")) true
Java in == Is the spatial address comparison of objects ,kotlin The comparison is the value of the current object , It belongs to structural comparison , Comparison of abbreviated values .
that "===" What is it? ?
var p1:People= People() var p2:People=People() println(p1===p2) false println(p1!==p2) true println("a"==="a") true
It can be seen that === and java Medium == It's consistent , Is the object address comparison ,!== and java in != It's an effect , Are for the determination of address control
9. Object type judgment is and !is
println("a" is String) true println("a" !is String) false
10. Use and definition of functions
java :public void methodName(String name) perhaps public String methodName(String name)
This is a common use , Before that, there is no return value , The latter one is to return a string
kotline: fun methodName(name:String) perhaps fun methodName(name:String):String
Function declaration :fun , Function name ( Parameters ), If there is a return value , Add... Outside the parameter brackets “: Return type ”,:String= Return to one String
// No return value
fun a(name:String){
printf(name)
}
// There is a return value
fun add(txt:Int):Int{
var result=txt+10
return result
}
10.1 Method inheritance
stay Java in , If you inherit a class , Implement a method of this class
@Override
public void log(String txt){
}
kotlin in , And java atypism , It's lowercase override stay fun front
override fun log(txt:String){
}
10.2 Class inheritance
// Parent class
open class Base{ open fun log(log:String?){ } }
// Subclass
class MyBase: Base() { // Method rewrite override fun log(log: String?) { super.log(log) } }
When the parent class declares the scope , use open, similar java public .
Inheritance direct use ":", If you want to use the methods of the parent class , The method must also be modified to open
10.3 abstract class :
Refer to the following information
10.4 Interface and interface inheritance
Refer to the following information
10.5 Parameter defaults ,
In the function , We often say that shapes participate in arguments . The default value of formal parameter is seldom heard ,java in , Formal parameters do not support default values , If not , The default message is null. however kotlin And java There's a difference
fun test(txt:String=" Hello "){
printf(txt)
}
If this method is called , Even if you don't transfer the value , The default is also adjustable , Print " Hello ",Java No way. .
There are three kinds of calls :
1.aa(txt = "hello") // Print :hello 2.aa(" hello ")// Print : hello 3.aa()// Print : Hello
The first belongs to named parameters , You can specify the value of one of the parameters , Others are the default
10.6 Variable parameters :
stay Java in , If we define a variable parameter , You can use "..." To modify ,String... list, Define a list A character array
stay kotlin in , Still support this behavior , By keyword vararg To describe
Java:
public void log(String... log){
}
kotlin:
fun log(vararg log:String){
}
10.7 Anonymous functions
Anonymous function types and lambda The expression is very detailed , There is no need to define a complete function , adopt lambda Expression to complete . You can refer to the following information
10.8 Generic functions
Generics in JAVA in , You are using an object that has been specified when it is constructed , Cannot construct by method , however kotlin, Methods can be used to construct
Java:
public class MyTest1<T> { public static void main(String[] args) { MyTest1<Integer> test1 = new MyTest1<Integer>(); System.out.println(test1.getLog(123)); } public T getLog(T name) { if (name instanceof Integer) { System.out.println("name is Int"); } return name; } }
kotlin:
fun <T> myLog(txt: String, name: T): T { return name; }
10.9 Inline function
inline fun <reified T : Number> setTextValue(arry: Array<T>) { for (item in arry) { if (item is Int) { println("item is int value=${item}") } } }
Format :inline fun<reified T: Parameters > Method name (value:T)
T Is an inline generic ,
call :
setTextValue<Int>(arry), Specifies the generic type , By method name <T>( Parameters )
10.10 Simplify functions
// Here is 1 To 100 Sum up
fun add(n: Int): Int { if (n <= 1) { return n } else { return n + add(n - 1) } } // Simplify function summation fun add1(n: Int): Int=if (n<=1) n else n+ add(n-1);
10.11 Tail recursive function
Tail recursive function refers to the tail value calling its own function repeatedly , stay fun Add a before the keyword tailrec To modify .
// If it is a tail recursive function , The compiler will use loops instead of recursion , Avoid spillovers ( Dead cycle )
tailrec fun cons(x:Double=1.0) :Double{ if (x==Math.abs(x)) return x else return cos(Math.abs(x)) }
10.12 Higher order function
The run passes an expression as a parameter , Form a high-order , as follows :
fun <T> maxLength(arry: Array<T>, grate: (T, T) -> Boolean): T? {
var max: T=arry[0]
for (item in arry) {
if (item == null || grate(item, max)) {
max = item;
}
}
return max;
} Maximum calculated length ,grate: (T, T) -> Boolean Is a parameter of a higher-order function , This writing belongs to lambda Anonymous writing of .
Call the following :
var list: Array<String>
list = arrayOf("lisi", "zhangshan", "wangwu", "jck")
var max=maxLength(list) { a, b -> a.length > b.length }
println("max=${max}")
Function followed by expression parameters :{ a, b -> a.length > b.length }
{ a, b -> a.length > b.length } yes lambda The same way of writing is as follows :
fun maxLengtj(a:T,b;t):Boolean{
var maxResult=if(a.length>b.length){
a
}else{
b
}
rreturn maxResukt
}
10.13 spread function :
An extension function is an extension of a function itself , stay java in , If a class provides a specified function , If you do not extend in the original class , This class will not provide additional functions :
public void Log{
public void log(String log){
system.out.printf(log);
}
}
Log Class provides only one method ,kotlin It can be extended on the original class .
If we want to be right String This function adds a new method , as follows
fun Class name . Method name
fun String.hello(){
var value=toString() print("hello value=${value}")
}
At this time, we have added a new one hello Method ,
Call the following :
var txt:String="nihao" txt.hllo()
remarks : The extension function can be used internally through this To quote yourself .
10.14 Date function
Format :
1. yyyy= Indicates the year
2.MM= Represents the month
3.dd: Indicates date day
4.HH= Express 24 hourly
5.hh= Express 12 hourly
6.mm= It means points
7.ss= For seconds
8.sss- millisecond
How to use :
// spread function
fun Date.newTime(): String { var time = SimpleDateFormat("HH:mm:ss:sss") return time.format(this) } // Common use fun time() { var time = SimpleDateFormat("yyyy-MM-dd HH:mm:ss:sss") var result = time.format(Date()) println(result) }
Call the following :
time() println(Date().newTime())
10.15 Simple interest object :
The simple interest object is Java It is common to use ,kotlin It also supports simple interest mode , adopt object Keyword to decorate the class .
object DataUtil { var newTime: String = "" get() { var time=SimpleDateFormat("yyyy-MM-dd") return time.format(Date()) } }
Use objects get() Method rewriting , You can omit defining methods , It can also be done by , The effect is the same
11. Class inheritance and construction
1. Class in use , The most common is the constructor , Inherit , initialization
Java:
1. Inherit , adopt extends To modify ,
public class V extends B
2. structure , Overloading of reference methods , That is, the method name is the same , Different parameters
kotlin:
Inherit : adopt “:” To modify
class MyBase :BaseA(){ override fun log() { super.log() } }
The base class needs to pass open To modify , The effect is similar to public,
open class BaseA { open fun log(){ println(javaClass.name) } }
Constructors :
kotlin Provides a default
init{
}
This class , Is executed before the constructor
class MyBase constructor() { init { println("MyBASES") } constructor(aa: String) { } constructor(aa: String, bb: String) { println("MyBASES constructor=${aa}${bb}") } }
Constructors can access after classes , Or add... In the method body , Support multiple constructions .
2. Inheritance of internal constructors
kotlin in , By inheritance ":" To mark , Constructors also support ,
class MyBase constructor(aa: String) { init { println("MyBASES") } constructor() : this("") { println("MyBASES1 constructor=") } constructor(aa: String, bb: String) : this("") { println("MyBASES1 constructor=") } }
If you want to call other constructors , adopt :+this Point to the constructor , Parameters match
But there's a problem , If the constructor uses this Point to , Then you need other constructors to inherit , Otherwise, an error will be reported
Primary constructor call expected
The above example provides three constructors , And only the method body can use the default constructor of method body or class name , A class constructor cannot reference an internal .
3. How to write a class constructor
class myBean(aa:String,bb:String){
}
perhaps
class MyBase constructor(aa: String) {
}
Can pass constructor To modify , You can omit it
4. Classification of constructors
kotlin The constructors of are divided into primary constructors and secondary constructors , The constructor following the main constructor class name , The constructor can be implemented by constructor To modify , You can also omit the keyword directly .
Secondary constructor : Except for the main constructor , Internal constructors of classes are called secondary constructors , adopt constructor To modify , The secondary constructor can reference the main Lycium barbarum , Or reference the secondary constructor , adopt this, But the primary constructor cannot reference the secondary constructor .
The main constructor does not write constructor Also called default constructor .
5. Parameters set and get modify
kotlin And Java Different , If you are defining a variable parameter , Provided by default set and get Method ,
class MyPeople { var name: String set(value) { println(value) } get() :String { return name } }
We can do it in set and get Modified value , Be careful :var name:String Can't add after ";" Number , Otherwise, the statement ends , No more set and get The method ,
All you need to do is call name Will call set, Can't be in set I quote name Variable , Otherwise, there will be a dead cycle . So in set in , Do not handle the current variable name , Otherwise, they will call each other , Into the dead cycle .
12. Companion
kotlin To cancel the static Static modification , Associated objects are used , This is an internal decoration , use companion object To modify
class MyPeople {
companion object NameTag { fun tag(name: String): String { if (name.startsWith("a")) { return "A"; } else if (name.startsWith("b")) { return "b" } else if (name.startsWith("c")) { return "c"; } else { return "d"; } } }
}
Call the following :
println(MyPeople.NameTag.tag("a")) println(MyPeople.tag("b"))
13. abstract class
Java Abstract classes exist in ,abstract To modify , Abstract classes only provide abstract methods , No specific method body is provided , stay kotlin in , There is also the modification of abstract classes . through abstract
abstract class Animation(kind: String = "") { var mkind = ""; init { mkind = kind; } abstract fun getName():String; fun log() { print(mkind) } }
class Kid(name: String = "") : Animation() { var mName = ""; init { mName = name; } override fun getName(): String { // TODO("Not yet implemented") return mName; } }
remarks : If the parameter has been assigned a default value , In the call , Can not pass value .
Use of constructor values : The value of the main constructor cannot be used directly , Only in
init{
}
// I quote , If the constructor has a default parameter value , It can be omitted .
Abstract classes and abstract methods are implemented through abstract To modify , Usage and Java The same principle
14. Interface
kotlin Interfaces are also supported , But the interface does not support constructors , But the interface supports a lot of things ,
interface KotlinInterface { fun log() { } abstract fun getName():String open fun setValue(name:String="") }
class TestInterface : KotlinInterface { override fun getName(): String { // TODO("Not yet implemented") return "hello" } override fun setValue(name: String) { // TODO("Not yet implemented") } }
14.1 Support method implementation , And can ,Java The interface of is an implementation body that does not support methods , Support abstract methods , Support method does not implement method body .
therefore kotlin Rich interface implementation , and Java There's a difference .
14.2 Interface as a callback
If the interface acts as a callback , You can't set abstract methods , Otherwise, an error will be prompted . The following interface is used as a parameter callback
interface MyClickListener { fun log() { } // abstract fun getName():String open fun setValue(name:String="") }
class TestMyClick { var clickListener: MyClickListener? = null fun setClick(click: MyClickListener) { clickListener = click } fun setName(name: String) { clickListener?.setValue(name) } } fun main() { var item=TestMyClick() item.setClick(object :MyClickListener{ override fun setValue(name: String) { TODO("Not yet implemented") } }) }
15. Nested class
and Java equally ,kotlin Internal classes are also supported
Java:
publi class A{
public class B{
}
}
kotlin:
class TestInllClass { class Child { var name = "" } } fun main() { var item = TestInllClass.Child() item.name = " Hello " print(item.name) }
There is only one decoration difference between nested classes and inner classes inner
1. Inner class :inner
class TestInllClass { inner class Child { var name = "" } }
inner keyword
A modifier represents an inner class
Nested classes are static and have nothing to do with external classes
Internal classes use this, Accessing the variables of an external class
inner class Child(kids: String = "child") { var name = "" var tag = "child" fun getname(): String { // External objects return "${[email protected]}" } fun getOun(): String { // own return "${this.tag}" } }
16. enumeration
Enumeration in Java Chinese support , stay kotlin Also support , It's all through enum To modify , however Java and kotlin There are some differences in the writing of
Java
public enum People { One,Two,Three,Four }
kotlin
enum class Peoples { One,Two,Three,Four }
kotlin Support constructor writing , That is to say, to different people item Assign different values
enum class Peoples(name:String=" The default value is ") { One("1"),Two("2"),Three("3"),Four }
17. Sealing class
The use of sealed classes is similar to enumeration , More like Java Enumeration usage in , adopt sealed Keyword class decoration
sealed class MifengClass{ class One(var name: String) : MifengClass() class Two(var name: String) : MifengClass() class Three(var name: String) : MifengClass() }
fun main() { print(MifengClass.One("12").name) }
18. Data class
Data classes are right java bean A new package for , We are Java in , It is often necessary to define a data for data parsing bean, Then explain , stay kotlin in , Just declare this class as a data class , Declare variables in the main constructor , The system will automatically set set and get Method
data class MyInfo(var name: String, var age: Int, var address: String)
We define a basic human information data
Use as follows :
fun main() { var people = MyInfo("zhangshan", 20, "jiangsu nanjing") print(people.info()) } // to Myinfo Add a new method , The above demo This kind of writing has been introduced fun MyInfo.info(): String { return "name={$name},age={$age},address={$address}" }
remarks :
1. Data class has at least one parameter , There is no empty attribute . That is, there is no object without attributes .
2. Constructor parameters are different from class constructors , Need to pass through var perhaps val modification .
3. Support copy Method , Support identical data .
17. Type conversion :as
Java Type conversion in , Just force the rotation (TypeClass)item that will do .kotlin Conversion is also supported , Need to pass through as
(a asPeople): Turn it out to be People The object of
Android:Kotlin library Anko The use of and grammar
Anko library : A brief description , Combine grammar , A detailed text will be produced
Layout introduction , Use it directly :
1. stay Android in , After the layout is introduced , To use the control, you need to findViewById perhaps new An object to use , however kotlin Provide a anko library , You can directly inject and use the layout in the current page
kotlinx.android.synthetic.main.
import kotlinx.android.synthetic.main.layout_kotline_one.*; Format :import kotlinx.android.synthetic.main.layoutname.*;
layoutname It is currently required to be introduced layout file name , hinder * It refers to all... Under the current layout view Of id, If you just want to introduce a control , hold * Change to the corresponding view Of id name that will do ,* Represents full injection
If you use controls :
for example :
2. The simplicity of the method :
Normally, we set a monitor :
btn_one.setOnClickListener( object : View.OnClickListener{ override fun onClick(v: View?) { //TODO("Not yet implemented") } })
anko library , Directly as follows :
btn_one.setOnClickListener { btn_one.text=" change " }
2.1 Object field assignment
// Native Android
btn_one.setText("sssss")
//kotlin Direct reference field
btn_one.text=" change "
2.2 Listening supports the return value , Set listening , There are two types of , One is anko How to write the library , The other is kotlin The object of writing
btn_one.setOnLongClickListener(object : View.OnLongClickListener { override fun onLongClick(v: View?): Boolean { //TODO("Not yet implemented") showToast("asd");true } })
// This kind of writing is also a continuation java Of lambda expression
toast(String msg) perhaps toast(int resid) yes kotlin Automatically supported .
toast There are two time intervals by default ,toast The offer is short , Use for a long time
longToast("123")
1. Interface setup :
Anonymous functions
btn_one?.setOnClickListener { v -> toast(" Hello ") } btn_one?.setOnClickListener { object:View.OnClickListener{ override fun onClick(v: View?) { // TODO("Not yet implemented") } } }
边栏推荐
猜你喜欢
随机推荐
新学派:不诈骗经济学
【观察】ObjectScale:重新定义下一代对象存储,戴尔科技的重构与创新
网络协议学习---LLDP协议学习
Oracle彻底卸载的完整步骤
Yolov5 changing the upper sampling mode
Flutter adds event listening | subscription
Is it safe to speculate in stocks by mobile phone?
Previous string inversion topic
撸一个随机数生成器
CSRF attack
Output reading: apply what you have learned
手机办理长投学堂证券开户靠谱安全吗?
有关计网的五种类型题
Floating window --- create a system floating window (can be dragged)
Software testing to avoid being dismissed during the probation period
TASK03|概率论
Network protocol learning -- lldp protocol learning
How to install SSL certificates in Microsoft Exchange 2010
I have summarized the knowledge points of JS [intermediate and advanced] for you
指南针在上面开股票账户安全吗?