XhstormR


On a dark desert highway Cool wind in my hair


Kotlin

Updated on 2017-04-13

https://kotlin.link/

https://kotlinlang.org/

https://devdocs.io/kotlin-reference/

https://kotlinlang.org/docs/reference/idioms.html

https://kotlinlang.org/docs/reference/basic-syntax.html

https://kotlinlang.org/api/latest/jvm/stdlib/index.html

https://try.kotlinlang.org/

https://kotlinlang.org/docs/kotlin-docs.pdf

https://github.com/JetBrains/kotlin/releases/latest

https://jcenter.bintray.com/org/jetbrains/kotlin/kotlin-stdlib/

Code

// ABC

/* DEF
   GHI */

-------------------------------------------------------

fun main(args: Array<String>) {     main 
    println("Hello World!")
}

-------------------------------------------------------

val a: String     
a = "ABC"
----
val a: String = "ABC"     
----
val a = "ABC"     

-------------------------------------------------------
Kotlin PrimitiveReference

var a = 123      get/set
val b = 123      get

-------------------------------------------------------

val a = """     原始字符串
fun helloWorld(val name : String) {
   println("Hello, world!")
}
"""

----

val a = "ABC"
val b = "$a 的长度为${a.length}"     

-------------------------------------------------------
Kotlin 

var a: String = null     
var b: String? = null      `?`  null

println(b.length)     访
println(b?.length)      `?.` 访 null
println(b!!.length)      `!!.` 访 null KotlinNullPointerException 

try {     try-catch
    println(b!!.length)
} catch (e: KotlinNullPointerException) {
    println("发生空指针异常!")
}

----

val a: String? = null

val b: Int = if (a != null) {     
    a.length      `?.` 访Smart Cast
} else {
    -1
}

val c: Int = if (a != null) a.length else -1      Java 

val d: Int = a?.length ?: -1     `?:`  null 

-------------------------------------------------------

fun sum(x: Int = 1, y: Int = 1): Unit {     
    println("$x+$y=${x + y}")     
}

fun sum(x: Int = 1, y: Int = 1) {      Unit (void)
    println("$x+$y=${x + y}")
}

fun sum(x: Int = 1, y: Int = 1) = println("$x+$y=${x + y}")      1 

sum()
sum(3)
sum(y = 3)     
----

1+1=2
3+1=4
1+3=4

-------------------------------------------------------

fun hello(name: String): String {
    return "Hello,$name"
}

fun hello(name: String) = "Hello,$name"      1 

-------------------------------------------------------

fun show(vararg str: String): Unit {     vararg [0,) Array<out T>
    for (s in str) {     str  Array<out String>
        print(s + " ")
    }
}

show()
----



val array: Array<String> = arrayOf("B", "C")
show("A", *array, "D")     spread `*`
----

A B C D
fun a(x: Int): Boolean {
    return x % 2 == 0
}

fun a(x: Int) = x % 2 == 0     (Int) -> Boolean Int Boolean

@kotlin.internal.InlineOnly
public inline fun println(message: Int) {     (Int) -> Unit Int Unit
    System.out.println(message)
}

val array = arrayOf(1, 2, 3, 4)

array     使 Lambda 
    .filter { it % 2 == 0 }
    .forEach { System.out.println(it) }

array     使
    .filter(::a)
    .forEach(::println)

val aa: (Int) -> Boolean = ::a      "函数类型"
val bb: (Int) -> Unit = ::println
array
    .filter(aa)
    .forEach(bb)
----

2
4

-------------------------------------------------------

     
             Lambda  Java8 
             
             
                      `::` 

val array: Array<Char> = arrayOf('A', 'B', 'C', 'D')

val list: MutableList<Int> = array.mapTo(mutableListOf(), { c -> c.toInt() })     mapTo {}  Lambda 

val list: MutableList<Int> = array.mapTo(mutableListOf()) { c -> c.toInt() }     

val list: MutableList<Int> = array.mapTo(mutableListOf()) { it.toInt() }     Lambda  `it` 

val list: MutableList<Int> = array.mapTo(mutableListOf(), Char::toInt)     Lambda 

println(list)
----

[65, 66, 67, 68]

-------------------------------------------------------

(1..5).reduce { _, _ -> 0 }     0 Lambda  `_` 

-------------------------------------------------------

fun a(i: Int): Int {
    return i * 2
}

fun a(i: Int) = i * 2     

val list = listOf(1, 2, 3, 4, 5)

list.map(fun(i: Int): Int {
    return i * 2
})

list.map(fun(i: Int) = i * 2)     
----
list.map(::a)     使
----
list.map { it * 2 }     Lambda 

-------------------------------------------------------

val list = listOf(1, 2, 3, 4, 5)

list.map({ i -> i * 2 })     

list.map() { i -> i * 2 }     

list.map { i -> i * 2 }     

list.map { it * 2 }     使 `it` 

-------------------------------------------------------
 this 

val stringBuilder = StringBuilder("123").apply a@ {      Lambda  this 
    println(this@a)
    "456".apply {
        println(this@apply)
        this@a.append(this@apply)
    }
}
println(stringBuilder)
----

123
456
123456

-------------------------------------------------------
 break 
 continue 

a@ for (x in 0..9) {
    b@ for (y in 10..19) {
        if (x == 5 && y == 15) {
            break@a     5 14
        }
        println("$x $y")
    }
}

-------------------------------------------------------
 return 
 return  Lambda 

Lambda 使 Inline

Closure

inline 使 Lambda 


Kotlin  inline 使 Lambda 


fun main(args: Array<String>) {
    a()
    println("————————————")
    b()
    println("————————————")
    c()
}
fun a() {
    val list1 = listOf(1, 2, 3, 4)
    println(list1)
    val list2 = list1.filter {     Lambda  fun a() Lambda 
        print("+ ")
        it % 2 == 0
        return
    }
    println()
    println(list2)
}
fun b() {
    val list1 = listOf(1, 2, 3, 4)
    println(list1)
    val list2 = list1.filter {     Lambda  filter
        print("+ ")
        return@filter it % 2 == 0      Lambda 
    }
    println()
    println(list2)
}
fun c() {
    val list1 = listOf(1, 2, 3, 4)
    println(list1)
    val list2 = list1.filter(fun(i: Int): Boolean {      filter
        print("+ ")
        return i % 2 == 0
    })
    println()
    println(list2)
}
----

[1, 2, 3, 4]
+

[1, 2, 3, 4]
+ + + +
[2, 4]

[1, 2, 3, 4]
+ + + +
[2, 4]

-------------------------------------------------------

fun main(args: Array<String>) {
    print(1)
    a {     return  1  a
        print(2)
        return@a      Lambda 
    }
    print(3)
    ----
    
    123

    print(1)
    b {     return  2  b  main Lambda 
        print(2)
        return
    }
    print(3)
    ----
    
    12

    print(1)
    b {     
        print(2)
        return@b      Lambda 
    }
    print(3)
    ----
    
    123
}

fun a(block: () -> Unit) {     
    block()
}

inline fun b(block: () -> Unit) {     
    block()
}

-------------------------------------------------------
 inline crossinlinenoinline 

inline fun a1(block: () -> Unit) {
    block()     
}

inline fun a2(crossinline block: () -> Unit) {      crossinline 
    thread { block() }     
    
    thread(block = { block() })     
}

inline fun x(block: () -> Unit) {
    thread(block = block)     
}

inline fun b(noinline block: () -> Unit) {      noinline  inline 
    thread(block = block)     
}
data class A(val id: Int, val name: String) : Closeable {      hashCodeequalstoStringcopy 
    override fun close() {
        println("close!")
    }
}

val a = A(1, "小明")     
val b = a.copy(name = "小张")     copy 
val (x, y) = a     component 

println("$x $y")     
println(a)
println(b)
----

1 
A(id=1, name=)
A(id=1, name=)

-------------------------------------------------------

with(a) {     
    println("[${this.id}, ${this.name}]")
}
----

[1, 小明]

-------------------------------------------------------

a.use {      Closeable使 use Closeable  Java7  ARM
    println("[${it.id}, ${it.name}]")
}
----

[1, 小明]
close!
val list = listOf("A", "B", "C")      List
val set = setOf("A", "B", "C")      Set
val map = mapOf("A" to 0, "B" to 1, "C" to 2)      MapKotlin  Map  Pair
val mutableList = mutableListOf("A", "B", "C")      List

println(list[0])
println(set.contains("A"))
println(map["A"])
----

A
true
0

for ((k, v) in map) {     Kotlin  Map  Pair
    println("$k -> $v")
}
----

A -> 0
B -> 1
C -> 2

-------------------------------------------------------

val list = listOf('A', 'B', 'C')

list.asIterable()     IterableEager
        .filter {
            println("filter:$it")
            true
        }
        .map {
            println("map:$it")
            it.toInt()
        }
        .first().let(::println)
----

filterA
filterB
filterC
mapA
mapB
mapC
65

list.asSequence()     SequenceLazy Java8 
        .filter {
            println("filter:$it")
            true
        }
        .map {
            println("map:$it")
            it.toInt()
        }
        .first().let(::println)
----

filterA
mapA
65

-------------------------------------------------------

val map: Map<String, List<Int>> = (1..9)
        .map { it * 3 }     
        .filter { it < 20 }     
        .groupBy { it % 2 == 0 }     
        .mapKeys {     
            if (it.key) {
                "偶数"
            } else {
                "奇数"
            }
        }
println(map)
----

{=[3, 9, 15], =[6, 12, 18]}

-------------------------------------------------------

val list1 = listOf(1..3, 4..6)     [1..3, 4..6]
val list2 = list1.flatMap { it }     [1, 2, 3, 4, 5, 6]     
val list3 = list2.map { it * 2 }     [2, 4, 6, 8, 10, 12]     

-------------------------------------------------------

val intRange = 1..4
val i = intRange.reduce { acc, i -> acc + i }     10
val j = intRange.fold(-5) { acc, i -> acc + i }     5

-------------------------------------------------------

val intRange = 1..10
val list = intRange.takeWhile { it % 5 != 0 }     [1, 2, 3, 4]

-------------------------------------------------------

val list: List<Any> = listOf("A", "B", "C", 1, 2, 3, 4)
list.filter { it is Int && it % 2 != 0 }.forEach(::println)
                       Smart Cast   
----

1
3
for
val intRange: IntRange = 1..5     
for (i in intRange) {
    print("$i ")
}

for (i in 1..5) {     1 2 3 4 5     
    print("$i ")
}

for (i in 1 until 5) {     1 2 3 4     
    print("$i ")
}

for (i in 2..10 step 2) {     2 4 6 8 10     
    print("$i ")
}

for (i in 10 downTo 5) {     10 9 8 7 6 5     
    print("$i ")
}

for (c in "Hello") {
    println(c)
}

if (i in 1..10) {
    println("YES")
} else {
    println("NO")
}


----
val strs = arrayOf("A", "B", "C")
for ((index, s) in strs.withIndex()) {      IndexedValue<T> 
    println("$index -> $s")
}
strs.forEachIndexed { index, s ->
    println("$index -> $s")
}
----

0 -> A
1 -> B
2 -> C
0 -> A
1 -> B
2 -> C

-------------------------------------------------------

whiledo...while
var i = 0
while (i < 5) {
    println(i)
    i++
}
do {
    println(i)
    i++
} while (i < 10)
----

0
1
2
3
4
5
6
7
8
9

-------------------------------------------------------
when Java  switch

val i = 8
when (i) {      switch
    0, 21 -> println("0 or 21")
    in 1..20 -> println("1 to 20")     
    !in 22..100 -> print("x<0 or x>100")     
    is Int -> print("is Int")     Smart Cast
    !is Int -> print("not Int")     
    else -> println("other")
}
when {      if-else if 
    i < 5 -> println("first block")
    i < 10 -> println("second block")
    else -> println("else block")
}

-------------------------------------------------------


val s = if (Math.random() - Math.random() > 0) {
    "成功"
} else {
    "失败"
}

val s = if (Math.random() - Math.random() > 0) "成功" else "失败"     

val s2 = when (Math.random() - Math.random() > 0) {
    true -> "成功"
    false -> "失败"
    else -> "失败"
}

-------------------------------------------------------

fun smartCast(x: Any): Boolean {     
    if (x is Boolean) {     
        return x
    } else if (x is Int) {
        return x > 0
    } else if (x is String) {
        return x.startsWith("Hello")
    } else {
        return false
    }
}

fun smartCast(x: Any): Boolean {      when  if-else if 
    when (x) {
        is Boolean -> return x
        is Int -> return x > 0
        is String -> return x.startsWith("Hello")
        else -> return false
    }
}

fun smartCast(x: Any): Boolean {      when 
    return when (x) {
        is Boolean -> x
        is Int -> x > 0
        is String -> x.startsWith("Hello")
        else -> false
    }
}

fun smartCast(x: Any) = when (x) {     
    is Boolean -> x
    is Int -> x > 0
    is String -> x.startsWith("Hello")
    else -> false
}
val any: Any = "ABC" as Any      java.lang.ClassCastException
----
if (any is String) {      instanceofSmart Cast
    println(any.length)     String
}
println(any.length)     Any length 

-------------------------------------------------------

fun String.abc(c: Char): String {     
    return this.filter { it != c }     false true 
}

fun String.abc(c: Char) = this.filter { it != c }

println("Hello".abc('l'))
----

Heo

fun String.Companion.abc() {     
    println("ABC")
}

fun String.Companion.abc() = println("ABC")

String.abc()     
----

ABC

val String.str1: String      val
    get() = "Hello"

println("".str1)
----

Hello

-------------------------------------------------------

1. 
2.  infix 
3.  1 

infix fun Int.abc(x: Int): Int {
    println("OK!")
    return this + x
}

println(1.abc(2).abc(3))     

println(1 abc 2 abc 3)     
----

OK!
OK!
6

-------------------------------------------------------
var <propertyName>: <PropertyType> [= <property_initializer>]
    [<getter>]
    [<setter>]

Kotlin 访 get/set
----
class A {
    var s: String = "Hi"
        get() {     get 
            println("Get")
            return field
        }
        set(value) {     set  private val  set  field
            if (value.startsWith("H")) {
                println("Set true")
                field = value     field sthis A
            } else {
                println("Set false")
            }
        }
}

val a = A()
a.s = "World"
println(a.s)
a.s = "Hello"
println(a.s)
----

Set false
Get
Hi
Set true
Get
Hello

-------------------------------------------------------
get/set 

class A {
    val s1: String by lazy {     访 get 
        println("123")                     线 synchronizedby lazy(LazyThreadSafetyMode.NONE) {}
        "AAA"
    }
    var s2: String by Delegates.observable("XXX") { prop, old, new ->     afterChange
        println("$old -> $new")               
    }
    var s3: String by Delegates.vetoable("XXX") { prop, old, new ->     beforeChange
        println("$old -> $new")             
        return@vetoable true     true false 
    }
}

val a = A()
println(a.s1)
a.s2 = "BBB"
println(a.s2)
a.s3 = "CCC"
println(a.s3)
----

123
AAA
XXX -> BBB
BBB
XXX -> CCC
CCC

 Map 
----
class User(val map: Map<String, Any?>) {      var  MutableMap
    val name: String by map      Key
    val age: Int by map
}

val user = User(mapOf("name" to "ABC", "age" to 25))     Key-ValueKotlin  Map  Pair
println("${user.name} ${user.age}")
----

ABC 25

-------------------------------------------------------


----
class A {
    val a: String by lazy {     val 使 by lazy {}访 get 
        println("123")
        "AAA"
    }
    lateinit var b: String      var 使 lateinit访 get  UninitializedPropertyAccessException 
}

val a = A()
println(a.a)
a.b = "BBB"
println(a.b)
----

123
AAA
BBB

-------------------------------------------------------

1.  object 
2.  String 
3.  val  get 

const val i = 5
class A {
    var name = ""
    var age = 20
}

class A constructor(var name: String = "", var age: Int = 20) {     
}

class A(var name: String = "", var age: Int = 20)      constructor {}

-------------------------------------------------------

data class A(var name: String, var age: Int) {     Kotlin 
    init {
        println("主构造函数 or 初始化块")
    }

    constructor(name: String) : this(name, 0) {     
        println("次构造函数1")
    }

    constructor(age: Int) : this("无名氏", age) {
        println("次构造函数2")
    }
}

println(A("张三", 20))
println(A("张三"))
println(A(20))
//println(A())     报错,没有无参构造函数
----

 or 
A(name=, age=20)
-
 or 
1
A(name=, age=0)
-
 or 
2
A(name=, age=20)

-------------------------------------------------------



data class A private constructor(var name: String, var des: String) {      private
    constructor(name: String) : this(name, "欢迎:$name")      public
}

println(A("张三"))
//println(A("张三", "ABC"))     报错,主构造函数为 private
----

A(name=, des=)

-------------------------------------------------------

import javafx.application.Application
import javafx.scene.Scene
import javafx.scene.layout.BorderPane
import javafx.stage.Stage

fun main(args: Array<String>) {     JavaFX
    Application.launch(A::class.java, *args)      KClass  Class 
}

class A : Application() {      Application 
    override fun start(primaryStage: Stage) {     
        primaryStage.title = "ABC"
        primaryStage.width = 400.toDouble()
        primaryStage.height = 300.toDouble()
        primaryStage.scene = Scene(BorderPane())
        primaryStage.show()
    }
}
interface A {      Java 
    val i: Int     
    val j: Int     访 var set() 
        get() = 2

    fun a()     
    fun b() {}     
}

class B : A {     
    override val i: Int
        get() = 1
    override fun a() {}
}

val a = object : A {     
    override val i: Int
        get() = 1
    override fun a() {}
}

-------------------------------------------------------


val o = object {
    val x = 1
    val y = 2
    val z = 3
    operator fun component1() = x     
    operator fun component2() = y     
    operator fun component3() = z     
}

val o = object : Any() {     Kotlin  Any 
    val x = 1
    val y = 2
    val z = 3
    operator fun component1() = x
    operator fun component2() = y
    operator fun component3() = z
}

val (x, y, z) = o     
println(x + y + z)     6
println(o.x + o.y + o.z)     6

-------------------------------------------------------


object MyObject {     Singleton
    val AUTHOR = "XhstormR"      static

    fun hello(): String {      static "@JvmStatic"  static  "@JvmField" Java 
        return "Hello $AUTHOR!"
    }
}

println(MyObject.AUTHOR)
println(MyObject.hello())
----

XhstormR
Hello XhstormR!

-------------------------------------------------------

open class A     A 

interface B     B 

class C : A(), B     C  A  B
operator
----
class A(var i: Int) {
    operator fun inc(): A {     a++
        i++
        return this
    }

    operator fun dec(): A {     a--
        i--
        return this
    }

    operator fun invoke(): Int {     a()
        return i
    }

    operator fun get(index: Int): Int {     a[0]
        return i
    }

    operator fun set(index: Int, int: Int) {     a[0] = 123
        i = int
    }

    operator fun compareTo(o: A): Int {     >,<,>=,<=
        return i.compareTo(o.i)
    }

    override operator fun equals(other: Any?): Boolean {     ==,!=IDE 
        if (this === other) return true
        if (other?.javaClass != javaClass) return false
        other as A
        if (i != other.i) return false
        return true
    }

    override fun hashCode(): Int {     IDE 
        return i
    }

    override fun toString(): String {     IDE 
        return "A(i=$i)"
    }
}
Java
class Test1 {
    static {
        System.out.println("1父类静态初始化块");
    }

    {
        System.out.println("2父类初始化块");
    }

    Test1() {
        System.out.println("3父类构造方法");
    }
}
----
class Test2 extends Test1 {
    static {
        System.out.println("1子类静态初始化块");
    }

    {
        System.out.println("2子类初始化块");
    }

    Test2() {
        System.out.println("3子类构造方法");
    }
}
----
class Initial {
    public static void main(String[] args) {
        Test1 a = new Test2();
    }
}
----

1
1
2
3
2
3

-------------------------------------------------------

Kotlin
open class Test1 {     Kotlin  Java  final open
    companion object {      Companionstatic 
        init {
            println("1父类静态初始化块")
        }
    }

    init {
        println("2父类初始化块")
        println("3父类构造函数(主)")
    }
}
----
class Test2 : Test1() {     
    companion object {      Companionstatic 
        init {
            println("1子类静态初始化块")
        }
    }

    init {
        println("2子类初始化块")
        println("3子类构造函数(主)")
    }
}
----
fun main(args: Array<String>) {
    val a: Test1 = Test2()     
    val companion = Test2.Companion     
}
----

1
1
2
3()
2
3()

-------------------------------------------------------

class A {
    companion object {      Companionstatic 
        var i = 0
        init {
            println("静态初始化块")
        }
    }

    init {
        println("${++i} 初始化块 构造函数(主)")
    }
}

A()
A()
A()
A()
----


1  ()
2  ()
3  ()
4  ()

-------------------------------------------------------

class A {
    companion object {      Companionstatic 
        val list = arrayListOf<A>()
    }

    init {
        list.add(this)
    }
}

A()
A()
A()
println(A.list)
----

[A@2f0e140b, A@7440e464, A@49476842]

-------------------------------------------------------

访

class Outer {
    private val bar = 1
    class Nested {     Java 
        fun foo() = 2
    }
}

Outer.Nested().foo()     

----

class Outer {
    private val bar = 1
    inner class Nested {     Java 
        fun foo() = bar     访
    }
}

Outer().Nested().foo()     
val array = arrayOfNulls<Int>(5)      5  null 
for (i in array.indices) {
    println(array[i])
}
----

null
null
null
null
null

-------------------------------------------------------

val s1 = "ABC"
val s2 = StringBuilder("ABC").toString()
println(s1 == s2)      operator  equals() !=
println(s1 === s2)     Java  `==` !==
----

true
false

-------------------------------------------------------

Kotlin
val a: Char = 'A'      Java  char
val b: Char? = 'B'      Java  Character
println(a)
println(b)

Convert to Java
char a = 65;
Character b = Character.valueOf('B');
System.out.println(a);
System.out.println(b);

----

Kotlin
val arrayOf = arrayOf(1, 2, 3)
val intArrayOf = intArrayOf(4, 5, 6)     

Convert to Java
Object[] elements$iv = new Integer[]{Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3)};
Integer[] arrayOf = (Integer[])((Object[])elements$iv);
int[] var10000 = new int[]{4, 5, 6};

-------------------------------------------------------

FileOutputStream("""D:\123.txt""", true).bufferedWriter().use { it.write("${LocalDateTime.now()}\n") }     
FileInputStream("""D:\123.txt""").bufferedReader().useLines { it.forEach(::println) }     

-------------------------------------------------------

println(String().javaClass)      Class 
println(String::class.java)      KClass  Class 
----

class java.lang.String     
class java.lang.String

Script

D:\Download\kotlinc\bin>kotlinc -script DeleteFile.kts

JavaScript

D:\Download\kotlinc\bin>kotlinc-js -output 123.js A.kt
D:\Download\kotlinc\lib\kotlin-stdlib-js.jar\kotlin.js
@JsName("main")
fun main(args: Array<String>) {
    js("""document.write(message+"<br/>")""")
    alert(message)
}

val message = "Hello JavaScript."

external fun alert(message: Any?)//暴露外部 API
<html>
<head>
    <meta charset="UTF-8">
    <title>123</title>
</head>
<body>
    <script type="text/javascript" src="kotlin.js"></script>
    <script type="text/javascript" src="123.js"></script>
</body>
</html>

Reference

TOP