数组
fun useDemo() {
var strArray = arrayOf("At", "Brod", "Cak")
strArray += "Dart"
println(strArray.joinToString("-"))
}
fun arrayDemo() {
val arr1 = arrayOf(1, 2, 3, 4, 5, 6)
println(arr1.joinToString())
val nullArray: Array<Int?> = arrayOfNulls(3)
println(nullArray.joinToString())
var exampleArray = emptyArray<String>()
var exampleArray2: Array<String> = emptyArray()
}
fun arrayDemo2() {
val twoDArray = Array(2) { Array<Int>(2) { 0 } }
println(twoDArray.contentDeepToString())
val threeDArray = Array(3) { Array(3) { Array<Int>(3) { 0 } } }
println(threeDArray.contentDeepToString())
}
fun operatorDemo() {
val intArray = arrayOf(1, 2, 3)
intArray[0] = 10
println(intArray.joinToString())
}
fun printAllStrings(vararg strings: String) {
for (string in strings) {
print(string)
}
}
fun varargDemo() {
val lettersArray = arrayOf("c", "d")
printAllStrings("a", "b", *lettersArray)
println()
}
fun toListDemo() {
val simpleArray = arrayOf("a", "b", "c", "c")
println(simpleArray.toSet())
println(simpleArray.toList())
val pairArray = arrayOf("apple" to 120, "banana" to 150, "cherry" to 90, "apple" to 140)
println(pairArray.joinToString())
println(pairArray.toMap())
}
fun arrayDemo3() {
val exampleArray = IntArray(5)
println(exampleArray.joinToString())
}
fun main() {
arrayDemo2()
operatorDemo()
varargDemo()
toListDemo()
}
类型检测和类型转换
package com.mcc.myapplication
fun getNum(): Number {
return 100F
}
fun isDemo() {
val obj = "hello"
if (obj is String) {
println("string length:${obj.length}")
}
val value = 1
if (value is Int) {
println("$value is Int")
}
val num = getNum()
if (num !is Int) {
println("$num not is Int")
}
}
fun transferDemo(x: Any) {
if (x is String) {
println("this param is string, and length:${x.length}")
}
}
fun transferDemo2(x: Any) {
if (x !is String) return
println("this param is string, and length:${x.length}")
}
fun transferDemo3(x: Any) {
if (x !is String || x.length == 0) return
if (x is String && x.length > 0) {
println("this param is string, and length:${x.length}")
}
}
fun transferDemo4(x: Any) {
when (x) {
is Int -> print(x + 1)
is String -> print(x.length + 1)
is IntArray -> print(x.sum())
}
}
fun transferDemo5(x: Any) {
val y: String? = x as String?
if (y != null) {
println("this param is string, and length:${x.length}")
}
}
fun transferDemo6(x: Any) {
val y: String? = x as? String
if (y != null) {
println("this param is string, and length:${x.length}")
}
}
fun main() {
isDemo()
transferDemo("world")
transferDemo2("gogogo")
transferDemo3("pythonX")
transferDemo4(intArrayOf(1, 2, 3, 4, 5))
transferDemo4(arrayOf(1, 2, 3, 4, 5, 6))
transferDemo6(111)
}
If 表达式
fun main() {
val a = 2
val b = 3
var max: Int? = null
if (a > b) {
max = a
} else {
max = b
}
max = if (a > b) a else b
println("max is $max")
val c = 10
val maxOrLimit = if (c > a) c else if (a > b) a else b
println("maxOrLimit is $maxOrLimit")
val max2 = if (a > b) {
print("Choose a,")
a
} else {
print("Choose b,")
b
}
println("max2 is $max2")
}
When 表达式
fun whenDemo1(x: Int) {
when (x) {
1 -> print("x == 1")
2 -> print("x == 2")
else -> {
print("x=$x is neither 1 nor 2")
}
}
println()
}
enum class Bit {
ZERO, ONE, TWO
}
fun getRandomBit(): Bit {
return Bit.ZERO
}
fun whenDemo2() {
val numericValue = when (getRandomBit()) {
Bit.ZERO -> 0
Bit.ONE -> 1
Bit.TWO -> 2
}
println(numericValue)
}
fun whenDemo3(x: Int, s: String) {
when (x) {
0, 1 -> print("x == 0 or x == 1")
else -> print("otherwise")
}
when (x) {
s.toInt() -> print("s encodes x")
else -> print("s does not encode x")
}
val validNumbers = listOf(3, 4, 5)
when (x) {
in 1..10 -> print("x is in the range")
in validNumbers -> print("x is valid")
!in 10..20 -> print("x is outside the range")
else -> print("none of the above")
}
}
fun main() {
whenDemo1(3)
whenDemo2()
}
For 循环
fun main() {
val ints = listOf(2, 3, 4, 5, 6)
for (item: Int in ints) {
print(item)
}
println()
for (i in 1..3) {
print(i)
}
println()
for (i in 6 downTo 0 step 2) {
print(i)
}
println()
val array = arrayOf("a", "b", "c")
for (i in array.indices) {
print(array[i])
}
println()
for ((index, value) in array.withIndex()) {
println("the element at $index is $value")
}
}
while 循环
while (x > 0) {
x--
}
do {
val y = retrieveData()
} while (y != null)
返回与跳转
fun demo1() {
loop@ for (i in 1..100) {
for (j in 1..100) {
if (j > 1) break@loop
println(j)
}
}
}
fun demo2() {
listOf(1, 2, 3, 4, 5).forEach {
if (it == 3) return
print(it)
}
println("this point is unreachable")
}
fun demo3() {
listOf(1, 2, 3, 4, 5).forEach lit@{
if (it == 3) return@lit
print(it)
}
print(" done with explicit label")
}
fun demo4() {
listOf(1, 2, 3, 4, 5).forEach {
if (it == 3) return@forEach
print(it)
}
print(" done with implicit label")
}
fun demo5() {
listOf(1, 2, 3, 4, 5).forEach(fun(value: Int) {
if (value == 3) return
print(value)
})
print(" done with anonymous function")
}
fun main() {
demo5()
}
异常
fun fail(message: String): Nothing {
throw IllegalArgumentException(message)
}
fun main(){
val input = "2"
val a: Int? = try { input.toInt() } catch (e: NumberFormatException) { null }
}
包与导入
package com.mcc.myapplication
fun printMessage() {
}
class Message { }
fun main() {
}
类与构造函数
package com.mcc.myapplication
import javax.inject.Inject
class Person { }
class Empty
class Student constructor(firstName: String) { }
class Customer public @Inject constructor(name: String) { }
class InitOrderDemo(name: String) {
val firstProperty = "First property: $name".also(::println)
init {
println("First initializer block that prints $name")
}
val secondProperty = "Second property: ${name.length}".also(::println)
init {
println("Second initializer block that prints ${name.length}")
}
}
class Person2(val firstName: String, val lastName: String, var age: Int)
class Person3(val firstName: String, val lastName: String, var isEmployed: Boolean = true)
class Person4(val pets: MutableList<Pet> = mutableListOf())
class Pet {
constructor(owner: Person4) {
owner.pets.add(this)
}
}
class Person5(val name: String) {
val children: MutableList<Person5> = mutableListOf()
constructor(name: String, parent: Person5) : this(name) {
parent.children.add(this)
}
}
class Constructors {
init {
println("Init block")
}
constructor(i: Int) {
println("Constructor i=$i")
}
constructor(i: Int, ss: String) : this(i) {
println("Constructor ss=$ss")
}
}
class DoCreateMe private constructor() { }
class DonotCreateMe private constructor() { }
class Customer2(val name: String = "", val age: Int = 18)
fun main() {
val p = Person()
val e = Empty()
val s = Student("SnZ")
InitOrderDemo("YourName")
Person2("morning", "cat", 30)
Person3("morning", "cat")
val p4 = Person4()
Pet(p4)
Pet(p4)
p4.pets.toList().joinToString().also(::println)
val p5 = Person5("ZhangSan")
Person5("ZhangXiao", p5)
Constructors(33, "mcc")
Customer2()
}
抽象类
abstract class Polygon {
abstract fun draw()
}
class Rectangle : Polygon() {
override fun draw() {
}
}
open class Polygon2 {
open fun draw() {
}
}
abstract class WildShape : Polygon2() {
abstract override fun draw()
}
类的继承
package com.mcc.myapplication
class Example : Any()
open class Base(p: Int)
class Derived(p: Int) : Base(p)
class MyClass : Base {
constructor(ctx: Int) : super(ctx)
constructor(ctx: Int, name: String) : super(ctx)
}
open class Shape {
open val vertexCount: Int = 0
open fun draw() {
}
fun fill() {
}
}
class Circle() : Shape() {
override fun draw() {
}
}
open class Rectangle() : Shape() {
override val vertexCount = 4
final override fun draw() {
}
}
interface Shape2 {
val vertexCount: Int
}
class Rectangle2(override val vertexCount: Int = 4) : Shape2
class Polygon2 : Shape2 {
override var vertexCount: Int = 0
}
fun main() {
}
类的属性