The previous article briefly introduced Kotlin’s basic data types (Introduction to Kotlin and Basic data types). This article focuses on Kotlin’s classes and objects, arrays and ranges, and type conversions.

Classes and objects

Class is an abstract concept, is the generalization of things with some characteristics, does not refer to any concrete things, and object is a concrete concept, and the opposite of class, used to describe a certain kind of specific individuals.

For example, “man” is a class, and “a kind-faced male engineer of 35 years old, 1.8 meters tall” is an object of this class.

In Kotlin, classes are written like this:

Class < class name > {< member >}

Without further ado, look at the code:

The open class (var personality: String, var looks: String, var height: String) {init {println (" created a ${this. JavaClass. SimpleName}, personality: $character, looks like: $appearance, height :$height ")}} Class beauty (character :String, appearance :String, height :String): person (character :String, appearance :String) String, height :String): person (personality, appearance, height) Array < String >) {val maid: beauty = beauty (" fury ", "kindness", "three" one meter) val orcs: handsome boy = handsome boy (" violent ", "thriller", "3 m")}Copy the code

Open decorates the class “people” to indicate that it can be inherited. In Kotlin, all classes are “final” by default and cannot be inherited.

A class can often have many concrete objects, but an object can be subordinate to only one class by nature.

A subclass has all the characteristics of its parent class and can also define its own characteristics

All classes ultimately inherit from Any

The concepts of “inheritance,” “superclasses,” and “subclasses” are similar to Java basics and will not be covered here.

Each class has its own init () method, which is called automatically when creating a new class.

Subclasses inherit from their parents by:.

As you can see, when creating a new subclass, val maid: beauty =… Val mInt:Int =… The form is the same,

In Kotlin, we can easily understand classes as a primitive type.

Class creation is also much simpler than Java, eliminating the need for “new” fields.

Is is used to determine whether a class is a subclass of another class.

For example, println(orcs are people) prints true

The result of the above code snippet:

Created a beauty, character: furious, appearance: kind, height: one meter three created a handsome boy, character: violent, appearance: thriller, height: three metersCopy the code

interval

“Interval” is a mathematical concept that represents the range between numbers, and it’s roughly the same as Kotlin’s definition of “interval”.

Range is a subclass of ClosedRange, and IntRange is the most commonly used in programming.

Basic writing:

0.. 100 means [0,100]

0 until 100

param in 0.. 100 is used to determine whether param is in the interval [0,100]

Some of you might ask: blogger, what’s the difference between [] and ()?

Emm… Dude, high school algebra.




Example:

Val mIntRange:IntRange = 0 until 100 UN main(args: Array<String>) {println(1 in mIntRange)} Output: trueCopy the code

An array of

That’s what we call an Array.

An array is defined as:

An impressive display or range of a particular type of thing or an ordered arrangement ,in partucular.

Do you see a number? So “array” doesn’t really have anything to do with “number”. An array is really a series of objects.


In Kotlin, the basic way to write an array is (in the case of String) :

val array:Array[String] = arrayOf(…)

Some basic operations on arrays:

Arrayp [I] the ith member

Array [I] = “wakaka” assigns the ith member

Array. length Indicates the array length

No different from Java.

In Kotlin, arrays of basic data types are customized to avoid unnecessary unboxing and boxing,


Look at the following example:

Val mCharArray:CharArray = charArrayOf('a','\n','\t','5','*','=') val mIntArray:IntArray = intArrayOf(2,4,6,8,10) val People mRenArray: Array < > = arrayOf (beauty (" caution ", "the masses", "one meter six"), a handsome boy (" hegemony ", "handsome", "one meter nine")) fun main (args: Array<String>) { println(mIntArray.slice(1.. IntRange for (I in mIntArray){println(I)}} [4, 6] 2 6 8 10Copy the code

For loops, the syntax will be covered in future articles.

Nullable types

Nullable types are primarily intended to minimize NPE at the compile level.

Declare a variable in Kotlin if the type is not followed by? You can’t just assign this variable to null and append the type? Becomes a nullable type, and nullable types can be directly assigned to null.

var name: String = null//Error:Null can not be a value of a non-null type String var name1: String? = null// A nullable type that can be assigned to nullCopy the code

Nullable types differ from ordinary types mainly in two operators, namely? And!! On.

Do we often get bored coding in Java? Using a parameter to declare null, using an array to declare null, using a class to declare null, really boring!!


But!! In Kotlin, this is a piece of cake.

Looking at the code example, we need only one operator:

fun main(args: Array<String>) { var name: String = "liuliqianxiao" print(name. Length)// = null) var name1: String? // print(name1.length)//Error:Only safe (? .). or non-null asserted (!! .). calls are allowed on a nullable receiver of type String? // Traditional usage if(name1! = null){print(name1. Length)} .length) // When name1 is null, null is printed // Or print(name1!! .length)// An NPE error occurs when name1 is null}Copy the code

Arguments are nullable types, such as val name: String = null,

But the call (name.length? .length), if the parameter is null, only null will be returned, and no null pointer exception will be thrown.

Class person () {var userName: String? = null} fun main(args: Array<String>) {var user: user? = null print(user? .userName? .length)//user==null or userName==nullCopy the code

Intelligent and secure casting

In Java, it is possible to throw a cast exception, which can cause the application to crash and the app to crash.

For example, if a subclass is converted to a parent class:

val sub:SubClass = parent as SubClass

If the type does not match, the program crashes

But in Kotlin:

val sub:SubClass? = parent as? SubClass

If the conversion fails, instead of throwing an exception, null is returned, which avoids crashes and gives you more leeway

What is the mechanism for intelligent type conversion?

That is, in Java:

Parent parent = new Child(); If (Parent instanceof Child){String name = ((Child) Parent).getName(); }Copy the code

Is it too much trouble? To call a method called Child, we need to convert parent to Child.

And in Kotlin:

val parent:Parent = Child()
if(parent is Child){
    var name:String = parent.getName()
}
Copy the code

The compiler pushes itself to the type, and we don’t have to reinvent the wheel at the code level.

This article focuses on classes and objects, arrays and ranges, nullable types and type conversions, and the next article begins with Kotlin syntax.

If you have any questions or if this article is wrong, please leave a comment.