-
Kotlin: We are different
-
Kotlin: A whole new game you haven’t played yet
-
Article 3: Kotlin for all: Coroutines Special
This article has been authorized to hongyang wechat public account reprint
As Kotlin has become more and more popular, learning Kotlin has become a rite of passage
Code is the best teacher
directory
-
Integrated Kotlin
-
The new keyword
-
This keyword
-
The class keyword
-
The extends keyword
-
The volatile keyword
-
The synchronized keyword
-
The final keyword
-
variable
-
Static constants
-
Define methods
-
Overloaded methods
-
Basic data types
-
Comparison of type
-
Comparison of object
-
Conversion operators
-
An array of
-
cycle
-
Angle of the loop
-
Senior cycle
-
Judgment is
-
The constructor
-
Create a class
-
Privatized set method
-
Privatized GET method
-
The enumeration
-
interface
-
Anonymous inner class
-
The inner class
-
The inner class accesses a variable of the same name as the outer class
-
An abstract class
-
Static variables and methods
-
Variable parameter
-
The generic
-
Construct code block
-
Static code block
-
Method code block
-
Ternary operator
-
Permission modifier
-
Suppression code warning
-
Annotation processor
Integrated Kotlin
- It needs to be in the project APP module first
build.gradle
Add configuration to file
apply plugin: 'kotlin-android'
android {
kotlinOptions {
jvmTarget = '1.8'}}Copy the code
- And then in the project root directory
build.gradle
Add the Kotlin plug-in configuration to the file
buildscript {
dependencies {
/ / Kotlin plugin: https://plugins.jetbrains.com/plugin/6954-kotlin
// noinspection GradleDependency
classpath 'org. Jetbrains. Kotlin: kotlin - gradle - plugin: 1.5.31'}}Copy the code
- It is important to note that here
Android Studio 4.2
For example, the integration isKotlin - gradle - plugin: 1.5.31
There is no issue with the version this Kotlin plugin uses and the current versionAndroid Studio
Version-dependent. If integration fails, you need to modify it to the appropriate version.
The new keyword
- Java write
Intent intent = new Intent();
Copy the code
- Kotlin spelled
var intent = Intent()
Copy the code
This keyword
- Java write
MainActivity.this
Copy the code
- Kotlin spelled
this@MainActivity
Copy the code
The class keyword
- Java write
MainActivity.class
Copy the code
- Kotlin spelled
MainActivity::class.java
Copy the code
The extends keyword
- Java write
public class MainActivity extends AppCompatActivity {}Copy the code
- Kotlin (in Kotlin, inherited classes must be modified with the open keyword)
class MainActivity : AppCompatActivity() {}Copy the code
The volatile keyword
- Java write
volatile ThreadPoolManager instance
Copy the code
- Kotlin spelled
@Volatile
var instance: ThreadPoolManager
Copy the code
The synchronized keyword
- Java write
Method on which synchronization locks are defined
public synchronized ThreadPoolManager getInstance(a) {}Copy the code
// define a synchronization lock in the
public ThreadPoolManager getInstance(a) {
synchronized (ThreadPoolManager.class) {
}
}
Copy the code
- Kotlin spelled
@Synchronized
fun getInstance(a): ThreadPoolManager? {}Copy the code
fun getInstance(a): ThreadPoolManager? {
synchronized(ThreadPoolManager::class.java, {
})
}
Copy the code
The final keyword
- Java write
// indicates that the variable cannot be reassigned
final String text = "";
Copy the code
// The representation method cannot be overridden
public final void test(a) {}Copy the code
// indicates that the class cannot be inherited
public final class MainActivity extends AppCompatActivity {}Copy the code
- Kotlin spelled
// indicates that the variable cannot be reassigned
val text = ""
Copy the code
// The representation method cannot be overridden
fun test(a){}Copy the code
// indicates that the class cannot be inherited
class MainActivity : AppCompatActivity() {}Copy the code
- Note that Kotlin classes and methods cannot be inherited or overridden by default and must be decorated with the open keyword if they are to be inherited or overridden
variable
- Java write
String text = "";
Copy the code
- Kotlin spelled
var text: String = ""
Copy the code
Static constants
- Java write
public class MainActivity extends AppCompatActivity {
static final String TEXT = "";
}
Copy the code
- Kotlin’s (note that static variables are defined above the class)
const val TEXT: String = ""
class MainActivity : AppCompatActivity() {}Copy the code
Define methods
- Java write
public void test(String message) {}Copy the code
- Kotlin (Unit has the same effect as void)
fun test(message: String): Unit{}Copy the code
// You can omit the return value Unit in Kotlin
fun test(message: String){}Copy the code
Overloaded methods
- Java write
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState); }}Copy the code
- Kotlin spelled
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?). {
super.onCreate(savedInstanceState)
}
}
Copy the code
Basic data types
- Java write
int i = 1;
long l = 2;
boolean b = true;
float f = 0;
double d = 0;
char c = 'A';
String s = "text";
Copy the code
- Kotlin spelled
var i: Int = 1
var l: Long = 2
var b: Boolean = true
var f: Float = 0F
var d: Double = 0.0
var c: Char = 'A'
var s: String = "text"
Copy the code
// To be more succinct, the type can be derived automatically
var i = 1
var l = 2
var b = true
var f = 0F
var d = 0.0
var c = 'A'
var s = "text"
Copy the code
Comparison of type
- Java write
if ("1" instanceof String) {
}
if(! ("2" instanceof String)) {
}
Copy the code
- Kotlin spelled
if ("1" is String) {
}
if ("2" !is String) {
}
Copy the code
Comparison of object
- Java write
// Compare two objects to see if they have the same content
if (object1.equals(object2)) {
}
if(! object3.equals(object4)) { }// Compare two objects to see if they are the same
if (object5 == object6) {
}
if(object7 ! = object8) { }Copy the code
- Kotlin spelled
// Compare two objects to see if they have the same content
if (object1 == object2) {
}
if(object3 ! = object4) { }// Compare two objects to see if they are the same
if (object5 === object6) {
}
if(object7 ! == object8) { }Copy the code
- Note: Kotlin
= =
And in Javaequals
The effect is the same, whereas Kotlin= = =
和Java
中= =
The effect is the same.
Conversion operators
- Java write
int number = 100;
System.out.println(String.format("Quantity of goods %d", number));
Copy the code
- Kotlin spelled
var number = 100
println("The quantity of goods is${number}")
Copy the code
// We can write it succinctly
var number = 100
println("The quantity of goods is$number")
Copy the code
// You can use \$if you don't want the string to be escaped
var number = 100
println("Item quantity = $number")
Copy the code
An array of
- Java write
int[] array1 = {1.2.3};
float[] array2 = {1f.2f.3f};
String[] array3 = {"1"."2"."3"};
Copy the code
- Kotlin spelled
val array1 = intArrayOf(1.2.3)
val array2 = floatArrayOf(1f.2f.3f)
val array3 = arrayListOf("1"."2"."3")
Copy the code
cycle
- Java write
String[] array = {"1"."2"."3"};
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
Copy the code
- Kotlin spelled
val array = arrayListOf("1"."2"."3")
for (i in array.indices) {
println(array[i])
}
Copy the code
Angle of the loop
- Java write
String[] array = {"1"."2"."3"};
for (int i = 1; i < array.length; i++) {
System.out.println(array[i]);
}
Copy the code
- Kotlin’s notation (which Kotlin calls intervals)
val array = arrayListOf("1"."2"."3")
for (i in IntRange(1, array.size - 1)) {
println(array[i])
}
Copy the code
// We can write it more succinctly
val array = arrayListOf("1"."2"."3")
for (i in 1..array.size - 1) {
println(array[i])
}
Copy the code
// The compiler prompts us to write it differently
val array = arrayListOf("1"."2"."3")
for (i in 1 until array.size) {
println(array[i])
}
Copy the code
Senior cycle
- Java write
String[] array = {"1"."2"."3"};
for (String text: array) {
System.out.println(text);
}
Copy the code
- Kotlin spelled
val array = arrayListOf("1"."2"."3")
for (text in array) {
println(text)
}
Copy the code
Judgment is
- Java write
int count = 1;
switch (count) {
case 0:
System.out.println(count);
break;
case 1:
case 2:
case 3:
System.out.println(count);
break;
case 5:
case 7:
System.out.println(count);
break;
default:
System.out.println(count);
break;
}
Copy the code
- Kotlin spelled
val count = 1
when (count) {
0 -> {
println(count)
}
in 1.3. -> {
println(count)
}
5.7 -> {
println(count)
}
else -> {
println(count)
}
}
Copy the code
Val count = 1 when (count) {0 -> println(count) in 1.. 3 -> println(count) 5, 7 -> println(count) else -> println(count) }Copy the code
The constructor
- Java write
public class MyView extends View {
public MyView(Context context) {
this(context, null);
}
public MyView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr); }}Copy the code
- Kotlin spelled
// The first way
class MyView : View {
constructor(context: Context) : this(context, null) {}constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0) {}constructor(context: Context, attrs: AttributeSet? , defStyleAttr:Int) : super(context, attrs, defStyleAttr) {
}
}
Copy the code
// The second way
class MyView : View {
constructor(context: Context) : this(context, null)
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
constructor(context: Context, attrs: AttributeSet? , defStyleAttr:Int) : super(context, attrs, defStyleAttr)
init{}}Copy the code
// The third way
class RegexEditText @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
init{}}Copy the code
// If there is only one constructor, you can write it like this
class MyView(context: Context) : View(context) {
init{}}Copy the code
Create a class
- Java write
public class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName(a) {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge(a) {
return age;
}
public void setAge(int age) {
this.age = age; }}Copy the code
Person person = new Person(Android Wheels.100);
person.setName("HJQ");
person.setAge(50);
System.out.println("name: " + person.getName() + ", age: " + person.getAge());
Copy the code
- (If you don’t want to expose the set method of a member variable, you can change var to val)
class Person {
var name: String? = null
get() = field
set(value) {field = value}
var age: Int = 0
get() = field
set(value) {field = value}
}
Copy the code
// We can write it more succinctly
class Person(var name: String, var age: Int)
Copy the code
var person = Person(Android Wheels.100)
person.name = "HJQ"
person.age = 50
println("name: {$person.name}, age: {$person.age}")
Copy the code
Privatized set method
- Java write
public class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName(a) {
return name;
}
private void setName(String name) {
this.name = name;
}
public int getAge(a) {
return age;
}
private void setAge(int age) {
this.age = age; }}Copy the code
- Kotlin spelled
class Person {
var name: String? = null
private set
var age: Int = 0
private set
}
Copy the code
Privatized GET method
- Java write
public class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
private String getName(a) {
return name;
}
private void setName(String name) {
this.name = name;
}
private int getAge(a) {
return age;
}
private void setAge(int age) {
this.age = age; }}Copy the code
- Kotlin spelled
class Person {
private var name: String? = null
private var age: Int = 0
}
Copy the code
The enumeration
- Java write
enum Sex {
MAN(1), WOMAN(2);
Sex(int type) {}
}
Copy the code
- Kotlin spelled
enum class Sex (var type: Int) {
MAN(1), WOMAN(2)}Copy the code
interface
- Java write
public interface Callback {
void onSuccess(a);
// New in JDK 8, interface methods support the default implementation
default void onFail(a) {}}Copy the code
- Kotlin spelled
interface Callback {
fun onSuccess(a)
fun onFail(a){}}Copy the code
Anonymous inner class
- Java write
post(new Runnable() {
@Override
public void run(a) {}});Copy the code
- Kotlin spelled
post(object : Runnable {
override fun run(a){}})Copy the code
The inner class
- Java write
public class MainActivity extends AppCompatActivity {
public class MyTask {}}Copy the code
- Kotlin spelled
class MainActivity : AppCompatActivity() {
inner class MyTask {}}Copy the code
The inner class accesses a variable of the same name as the outer class
- Java write
String name = Android Wheels;
public class MyTask {
String name = "HJQ";
public void show(a) {
System.out.println(name + "-" + MainActivity.this.name); }}Copy the code
- Kotlin spelled
var name = Android Wheels
inner class MyTask {
var name = "HJQ"
fun show(a) {
println(name + "-" + this@MainActivity.name)
}
}
Copy the code
An abstract class
- Java write
public abstract class BaseActivity extends AppCompatActivity implements Runnable {
abstract void init(a);
}
Copy the code
- Kotlin spelled
abstract class BaseActivity : AppCompatActivity(), Runnable {
abstract fun init(a)
}
Copy the code
Static variables and methods
- Java write
public class ToastUtils {
public static Toast toast;
public static void show(a) { toast.show(); }}Copy the code
- Kotlin’s way of writing it (Kotlin called it an associated object)
companion object ToastUtils {
var toast: Toast? = null
fun show(a){ toast? .show() } }Copy the code
Variable parameter
- Java write
public int add(int. array) {
int count = 0;
for (int i: array) {
count += i;
}
return count;
}
Copy the code
- Kotlin spelled
fun add(vararg array: Int): Int {
var count = 0
//for (i in array) {
// count += i
/ /}
array.forEach {
count += it
}
return count
}
Copy the code
The generic
- Java write
public class Bean<T extends String> {
T data;
public Bean(T t) {
this.data = t; }}Copy the code
Bean<String> bean = new Bean<>("666666");
Copy the code
- Kotlin spelled
class Bean<T : Comparable<String>>(t: T) {
var data = t
}
Copy the code
var bean = Bean<String>("666666")
Copy the code
// We can write it more succinctly
var bean = Bean("666666")
Copy the code
Construct code block
- Java write
public class MainActivity extends AppCompatActivity {
int number;
{
number = 1; }}Copy the code
- Kotlin spelled
class MainActivity : AppCompatActivity() {
var number = 0
init {
number = 1}}Copy the code
Static code block
- Java write
public class MainActivity extends AppCompatActivity {
static int number;
static {
number = 1; }}Copy the code
- Kotlin spelled
class MainActivity : AppCompatActivity() {
companion object {
var number = 0
init {
number = 1}}}Copy the code
Method code block
- Java write
void test(a){{int a = 1; }}Copy the code
- Kotlin spelled
fun test(a) {
run {
var a =1}}Copy the code
Ternary operator
- Java write
int c = a > b ? a : b;
Copy the code
- Kotlin spelled
var c = if (a > b) a else b
Copy the code
Permission modifier
- Java (default is
default
)
The modifier | role |
---|---|
public | All classes visible |
protected | Subclasses visible |
default | Classes under the same package are visible |
private | Only visible to its own class |
- Kotlin (default
public
)
The modifier | role |
---|---|
public | All classes visible |
internal | Visible as classes under Module |
protected | Subclasses visible |
private | Only visible to its own class |
Suppression code warning
- Java write
@SuppressWarnings("unused")
@SuppressLint("ClickableViewAccessibility")
Copy the code
- Kotlin spelled
@Suppress("unused")
@Suppress("ClickableViewAccessibility")
Copy the code
Annotation processor
- Java write
annotationProcessor 'com. Making. Bumptech. Glide: the compiler: 4.12.0'
Copy the code
- Kotlin spelled
apply plugin : 'kotlin-kapt'
Copy the code
kapt 'com. Making. Bumptech. Glide: the compiler: 4.12.0'
Copy the code
- If Kotlin still uses annotationProcessor to integrate annotation processors, errors will be reported and compilation will fail