Kotlin 数据类型

使用var定义变量

var b: Int = 1
// val 创建常量
val a = 1

所有的数据类型都是对象 Int

public actual class Int private constructor() : Number(), Comparable<Int>

public actual abstract class Number {
/**
* Returns the value of this number as a [Double], which may involve rounding.
*/
public actual abstract fun toDouble(): Double

/**
* Returns the value of this number as a [Float], which may involve rounding.
*/
public actual abstract fun toFloat(): Float

/**
* Returns the value of this number as a [Long], which may involve rounding or truncation.
*/
public actual abstract fun toLong(): Long

/**
* Returns the value of this number as an [Int], which may involve rounding or truncation.
*/
public actual abstract fun toInt(): Int

/**
* Returns the [Char] with the numeric value equal to this number, truncated to 16 bits if appropriate.
*/
@Deprecated("Direct conversion to Char is deprecated. Use toInt().toChar() or Char constructor instead.\nIf you override toChar() function in your Number inheritor, it's recommended to gradually deprecate the overriding function and then remove it.\nSee https://youtrack.jetbrains.com/issue/KT-46465 for details about the migration", ReplaceWith("this.toInt().toChar()"))
@DeprecatedSinceKotlin(warningSince = "1.9", errorSince = "2.3")
public actual open fun toChar(): Char {
return toInt().toChar()
}

kotlin的变量可以自动推导,赋初值的是就可以自动推导

var b: Int = 1

var b = 1

kotlin数字+的时候调用的是plus方法,此方法没有string的参数,所以不会像java一样自动转成字符串,而是编译错误

var b = 1
b + "2"

None of the following candidates is applicable:

fun plus(other: Byte): Int:
Argument type mismatch: actual type is 'String', but 'Byte' was expected.

fun plus(other: Short): Int:
Argument type mismatch: actual type is 'String', but 'Short' was expected.

fun plus(other: Int): Int:
Argument type mismatch: actual type is 'String', but 'Int' was expected.

fun plus(other: Long): Long:
Argument type mismatch: actual type is 'String', but 'Long' was expected.

fun plus(other: Float): Float:
Argument type mismatch: actual type is 'String', but 'Float' was expected.

fun plus(other: Double): Double:
Argument type mismatch: actual type is 'String', but 'Double' was expected.

不过string + 数字是可以的,因为string的plus是any类型的参数,相当于调用了.toString()的方法再相加

var b = 1
"3" + b

@IntrinsicConstEvaluation
public final operator fun plus(
other: Any?
): String
// 默认的数字是Int,想要转换长整型需要加L
var b = 1 //Int
var b = 1L //Long
// 默认小数是double,想要浮点加个F
var c = 1.2 //Double
var c = 1.2f //Float
var c = 1.2F //Float

kotlin所有的Int、Double这些基本数据类型都是对象,所以没有继承关系,比如想要byte去转Int就是错误的

kotlin里面的string,看到里面是有继承character的,所以通过get方法是可以获取到目标位置的字符

public actual class String : Comparable<String>, CharSequence {}

val string: String = "String"
println(string.get(0))
println(string[0])

kotlin中的any就像java中的object,相当于所有类的一个基类,所有类都有equals、hashCode和toString方法,那么kotlin中String的比较可以直接equals去做比较,也可以直接用==

/**
* The root of the Kotlin class hierarchy. Every Kotlin class has [Any] as a superclass.
*/
public actual open class Any {
/**
* Indicates whether some other object is "equal to" this one.
*
* Implementations must fulfil the following requirements:
* * Reflexive: for any non-null value `x`, `x.equals(x)` should return true.
* * Symmetric: for any non-null values `x` and `y`, `x.equals(y)` should return true if and only if `y.equals(x)` returns true.
* * Transitive: for any non-null values `x`, `y`, and `z`, if `x.equals(y)` returns true and `y.equals(z)` returns true, then `x.equals(z)` should return true.
* * Consistent: for any non-null values `x` and `y`, multiple invocations of `x.equals(y)` consistently return true or consistently return false, provided no information used in `equals` comparisons on the objects is modified.
* * Never equal to null: for any non-null value `x`, `x.equals(null)` should return false.
*
* Read more about [equality](https://kotlinlang.org/docs/reference/equality.html) in Kotlin.
*/
public actual open operator fun equals(other: Any?): Boolean

/**
* Returns a hash code value for the object.
*
* The general contract of `hashCode` is:
* * Whenever it is invoked on the same object more than once, the `hashCode` method must consistently return the same integer, provided no information used in `equals` comparisons on the object is modified.
* * If two objects are equal according to the `equals()` method, then calling the `hashCode` method on each of the two objects must produce the same integer result.
*/
public actual open fun hashCode(): Int

/**
* Returns a string representation of the object.
*/
public actual open fun toString(): String
}

String的拼接

val b = """
asd
asd
asd
""".trimIndent()
println("Str$b ing")
println("Str${b}ing")

然后是一些常见的集合类型

创建array,使用的是arrayOf()

public actual inline fun <reified T> arrayOf(vararg elements: T): Array<T>

返回的是一个空的array,有这些get、set、size的方法和属性

/**
* A generic array of objects.
* Instances of this class are represented as `T[]`.
* Array instances can be created using the [arrayOf], [arrayOfNulls] and [emptyArray]
* standard library functions.
*
* See [Kotlin language documentation](https://kotlinlang.org/docs/arrays.html)
* for more information on arrays.
*/
public actual class Array<T> {
/**
* Creates a new array of the specified [size], where each element is calculated by calling the specified
* [init] function.
*
* The function [init] is called for each array element sequentially starting from the first one.
* It should return the value for an array element given its index.
*
* @throws RuntimeException if the specified [size] is negative.
*/
@Suppress("WRONG_MODIFIER_TARGET")
public actual inline constructor(size: Int, init: (Int) -> T)

/**
* Returns the array element at the given [index].
*
* This method can be called using the index operator:
* ```
* value = array[index]
* ```
*
* If the [index] is out of bounds of this array, throws an [IndexOutOfBoundsException].
*/
public actual operator fun get(index: Int): T

/**
* Sets the array element at the given [index] to the given [value].
*
* This method can be called using the index operator:
* ```
* array[index] = value
* ```
*
* If the [index] is out of bounds of this array, throws an [IndexOutOfBoundsException].
*/
public actual operator fun set(index: Int, value: T): Unit

/**
* Returns the number of elements in the array.
*/
public actual val size: Int

/** Creates an [Iterator] for iterating over the elements of the array. */
public actual operator fun iterator(): Iterator<T>
}

还有各种各样的array。比如intarray,stringarray这些

然后List,创建就是listof,返回一个空的list,方法属性也很类似

public inline fun <T> listOf(): List<T> = emptyList()

/**
* A generic ordered collection of elements. The interface allows iterating over contained elements,
* accessing elements by index, checking if a list contains some elements, and searching indices for particular values.
* Complex operations are built upon this functionality and provided in form of [kotlin.collections] extension functions.
*
* Functions in this interface support only read-only access to the list;
* read/write access is supported through the [MutableList] interface.
*
* In addition to a regular iteration, it is possible to obtain [ListIterator] using [listIterator] that provides
* bidirectional iteration facilities, and allows accessing elements' indices in addition to their values.
*
* It is possible to get a view over a continuous span of elements using [subList].
*
* Unlike [Set], lists can contain duplicate elements.
*
* Unlike [Collection] implementations, [List] implementations must override [Any.toString], [Any.equals] and [Any.hashCode] functions
* and provide implementations such that:
* - [List.toString] should return a string containing string representation of contained elements in exact same order
* these elements are stored within the list.
* - [List.equals] should consider two lists equal if and only if they contain the same number of elements and each element
* in one list is equal to an element in another list at the same index.
* - [List.hashCode] should be computed as a combination of elements' hash codes using the following algorithm:
* ```kotlin
* var hashCode: Int = 1
* for (element in this) hashCode = hashCode * 31 + element?.hashCode() ?: 0
* ```
*
* By convention, [List] implementations are usually also implement [java.io.Serializable].
*
* @param E the type of elements contained in the list. The list is covariant in its element type.
*/
public actual interface List<out E> : Collection<E> {
// Query Operations

actual override val size: Int
actual override fun isEmpty(): Boolean
actual override fun contains(element: @UnsafeVariance E): Boolean
actual override fun iterator(): Iterator<E>

// Bulk Operations
actual override fun containsAll(elements: Collection<@UnsafeVariance E>): Boolean

// Positional Access Operations
/**
* Returns the element at the specified index in the list.
*
* @throws IndexOutOfBoundsException if [index] is less than zero or greater than or equal to [size] of this list.
*
* @sample samples.collections.Collections.Lists.get
*/
public actual operator fun get(index: Int): E

// Search Operations
/**
* Returns the index of the first occurrence of the specified element in the list, or `-1` if the specified
* element is not contained in the list.
*
* For lists containing more than [Int.MAX_VALUE] elements, a result of this function is unspecified.
*
* @sample samples.collections.Collections.Lists.indexOf
*/
public actual fun indexOf(element: @UnsafeVariance E): Int

/**
* Returns the index of the last occurrence of the specified element in the list, or -1 if the specified
* element is not contained in the list.
*
* For lists containing more than [Int.MAX_VALUE] elements, a result of this function is unspecified.
*
* @sample samples.collections.Collections.Lists.lastIndexOf
*/
public actual fun lastIndexOf(element: @UnsafeVariance E): Int

// List Iterators
/**
* Returns a list iterator over the elements in this list (in proper sequence).
*/
public actual fun listIterator(): ListIterator<E>

/**
* Returns a list iterator over the elements in this list (in proper sequence), starting at the specified [index].
*
* @throws IndexOutOfBoundsException if [index] is less than zero or greater than or equal to [size] of this list.
*/
public actual fun listIterator(index: Int): ListIterator<E>

// View
/**
* Returns a view of the portion of this list between the specified [fromIndex] (inclusive) and [toIndex] (exclusive).
* The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list.
*
* Structural changes in the base list make the behavior of the view unspecified.
*
* @throws IndexOutOfBoundsException if [fromIndex] less than zero or [toIndex] greater than [size] of this list.
* @throws IllegalArgumentException of [fromIndex] is greater than [toIndex].
*
* @sample samples.collections.Collections.Lists.subList
*/
public actual fun subList(fromIndex: Int, toIndex: Int): List<E>
}

但是发现list不能增也不能删

可变的list需要使用mutableList去创建

mutableListOf<>()