kotlin 学习例子

https://github.com/yangzmpang/springboot_kotlin_mysql_test

这两天学习了下kotlin 真的很好,感觉java 要凉了, 写了点代码,与时俱进:

import java.util.*

// 生成单例的使用
object appLog{
    fun write(){
        println("write..")
    }
}

class Car() {
    var color: String = "red"
    var doors = 3

    override fun toString() = "$color car with $doors doors"
}

// 多返回值测试
data class Result(val result: Int, val status: String)
fun fac(n: Int): Result{
    if(n == 1){
        return Result(1, "成功")
    } else if(n > 1) {
        return Result(fac(n - 1).result * n, "成功")
    } else {
        return Result(-1, "参数必须大于0")
    }
}

fun arrayTest(){
    val arr2 = arrayOfNulls<String>(4)

    arr2[0] = "a"
    arr2[1] = "b"
    arr2[2] = "c"

    // 编译时就可以发现出问题了
    //arr2[5] = "e"

    for (item in arr2) {
        println(item)
    }

    // 打印index
    for (idx in arr2.indices) {
        println(arr2[idx])
    }

    arr2.forEach({ e -> print("$e") })

    // 分片的使用
    var arr = arrayOf( "1", "2", "3","4","5", "6", "7","8")
    val slice = arr.sliceArray(1..3)
    for( ic in slice )
        println( ic )

    // sort array
    val nums = arrayOf(7, 3, 3, 4, 5, 9, 1)

    val sortedNums = nums.sortedArray()
    println(Arrays.toString(sortedNums))

    val sortedNumsDesc = nums.sortedArrayDescending()
    println(Arrays.toString(sortedNumsDesc))
}

// test
fun setTest(){
    var mutableSet = mutableSetOf("Java", "Kotlin", "Go")

    mutableSet.add("swift")
    mutableSet.add("c#")
    mutableSet.add("c#")
    mutableSet.add("swift")

    for( i in mutableSet ){
        println( i )
    }

    if ( "c#" in mutableSet ){
        println("find c#");
    }

    println( mutableSet.indexOf( "c#" ))
    println( mutableSet.indexOf( "Java") )

    var mutableSet2 = mutableSetOf("Lua", "kotlin", "c#")
    println( mutableSet + mutableSet2 )
    println( mutableSet - mutableSet2 )

    mutableSet.remove( "c#")
    println(mutableSet)
    mutableSet.removeAll(setOf("Java","Go"))
    println(mutableSet)

    var set = mutableSetOf("a", "b" , "c")

    var it = set.iterator() // 返回MutableIterator
    while(it.hasNext()) {
        var e = it.next()
        println(e)
        // 遍历时删除元素
        if (e.length < 3) {
            it.remove()
        }
    }
}

fun mapTest(){
    val chars = mapOf(97 to "a", 98 to "b", 120 to "x")
    println(chars)

    val user = mapOf("name" to "Luke", "age" to "23")
    println(user)

    val items = mapOf("coins" to 12, "books" to 45, "cups" to 33)

    println("Entries: " + items.entries)
    println("Keys:" + items.keys)
    println("Values:" + items.values)

    val user2 = mutableMapOf("name" to "John Doe", "occupation" to "programmer")
    println(user2)

    user2.put("location2", "USA2")
    user2["location"] = "USA"
    println(user2)

    // get value
    if (items.containsKey("location"))
       println(user2.getValue("location"))

    user2.remove("occupation")
    println(user2)

    // walk all
    user2.forEach {
        (k, v) -> println("key: [$v] value:[$k]")
    }
    for (en in user2.entries) {
        println("${en.key} -> ${en.value}")
    }
    // 先遍历Map的key对,再通过key获取value
    for (key in user2.keys ) {
        println("${key} -> ${user2[key]}")
    }
    // 直接用for-in循环遍历Map
    for( (key,value) in user2){
        println("${key} -> ${value}")
    }

    val items2 = mapOf("A" to 90, "B" to 80, "C" to 70, "D" to 60, "E" to 50)

    val filtered = items2.filterKeys { it == "A" || it == "C" }
    println(filtered)

    val filtered2 = items2.filterValues { it >= 70 }
    println(filtered2)

    //  so cool !!!
    val filtered3 = items2.filter { it.key == "A" || it.value == 50 }
    println(filtered3)
}

fun listTest(){
    val n = mutableListOf(3, 4, 5)

    n.add(6)
    n.add(7)
    n.addAll(listOf(8, 9, 10))
    n.add(0, 0)
    n.add(1, 1)
    n.add(2, 2)

    fun testDrop() {
        val nums = listOf(4, 5, 3, 2, 1, -1, 7, 6, -8, 9, -12)

        val nums2 = nums.drop(3)
        println(nums2)

        val nums3 = nums.dropLast(3)
        println(nums3)

        val nums4 = nums.sorted().dropWhile { e -> e < 0 }
        println(nums4)

        val nums5 = nums.sorted().dropLastWhile { e -> e > 0 }
        println(nums5)
    }

    fun testTake(){
        val nums = listOf(4, 5, 3, 2, 1, -1, 7, 6, -8, 9, -12)

        val nums2 = nums.take(3)
        println(nums2)

        val nums3 = nums.takeLast(3)
        println(nums3)

        val nums4 = nums.sorted().take(3)
        println(nums4)

        val nums5 = nums.takeWhile { e -> e > 0 }
        println(nums5)
    }

    println(testDrop())
    println(testTake())
}

fun stringTest(){

    //  查找分割
    val email = "yangzm@sina.com@tail"
    val index = email.indexOf('@')

    if ( index > 0 ) {
        val domain: String? = email.substringAfterLast("@")
        val left = email.substringBefore("@")
        val mid = email.substringAfter("@")
        val a:Int = 0
    }

    // 替换
    val s = "123abc123def"

    // 全部替换
    val b = s.replace("123","aaa")
    println(b)

    // 替换第一个
    val c = s.replaceFirst("123","aaa")
    println(c)

    val str = "1,2,3,4"
    val v2 = str.split(",")
    println( v2 )

    // 多行的string,写在一起
    val text = """
        123 abc;
        456,789?;
        """
    println( text.trimIndent() )


}

// http://zetcode.com/all/#kotlin
fun main(a:Array<String>)
{
    val v = CJava()

    println( v.name )

    // 循环递增
    for (i in 0 .. 5){
        print("i => $i \t")
    }

    // 循环5次,且步长为1的递减
    for (i in 15 downTo 11){
        print("i => $i \t")
    }

    println( "appdata 单例 + ${AppData.add(123,456)}");
    println( "单例二: ${appLog.write()}");

    //  创造模式的使用
    val cdef = Car().apply {
        color = "yellow"
        doors = 5
    }

    if ( cdef is Car ) {
        println("begin..");
        println(cdef);
        println("end..");
    }
    else
        println("error");

    val(av,bv) = fac( 6 );
    println(av)
    println(bv)

    //setTest()
    //arrayTest()
    //mapTest()
    //listTest()
    stringTest()
}

Appdata.kt 这个用来测试放到单独的文件的情况:

// 生成单例的使用
object AppData {
    fun add( a: Int, b: Int ):Int{
        return a + b;
    }
}

 测试单独调用 java 类:

public class CJava {
    public String getName() {
        return "bill";
    }
}

 get post 的测试: 用的库是okhttp 

        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>3.9.0</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.module</groupId>
            <artifactId>jackson-module-kotlin</artifactId>
            <version>2.9.8</version>
        </dependency>
package com.yzm

import com.fasterxml.jackson.databind.ObjectMapper
import okhttp3.MediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import java.net.URL

fun get() {
    val client = OkHttpClient()
    val url = URL("https://reqres.in/api/users?page=2")

    val request = Request.Builder()
        .url(url)
        .get()
        .build()

    val response = client.newCall(request).execute()

    val responseBody = response.body()!!.string()

    //Response
    println("Response Body: " + responseBody)

    //we could use jackson if we got a JSON
    val mapperAll = ObjectMapper()
    val objData = mapperAll.readTree(responseBody)

    objData.get("data").forEachIndexed { index, jsonNode ->
        println("$index $jsonNode")
    }
}


fun post() {
    val client = OkHttpClient()
    val url = URL("https://reqres.in/api/users")

    //just a string
    var jsonString = "{\"name\": \"Rolando\", \"job\": \"Fakeador\"}"

    //or using jackson
    val mapperAll = ObjectMapper()
    val jacksonObj = mapperAll.createObjectNode()
    jacksonObj.put("name", "Rolando")
    jacksonObj.put("job", "Fakeador")
    val jacksonString = jacksonObj.toString()

    val JSON2 = MediaType.parse("application/json; charset=utf-8")
    val body = RequestBody.create(JSON2, jacksonString)

    val request = Request.Builder()
        .url(url)
        .post(body)
        .build()

    val response = client.newCall(request).execute()

    val responseBody = response.body()!!.string()

    //Response
    println("Response Body: " + responseBody)

    //we could use jackson if we got a JSON
    val objData = mapperAll.readTree(responseBody)

    println("My name is " + objData.get("name").textValue() + ", and I'm a " + objData.get("job").textValue() + ".")
}


fun main(args: Array<String>) {

    //get()
    post()

}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值