kotlin example

Utils

inline fun  T.getLogger(): Logger {
  return LoggerFactory.getLogger(T::class.java)
}

infix fun RoutingContext.jsonReply(obj: Any?) {
  response().putHeader(HttpHeaders.CONTENT_TYPE, "application/json; charset=utf-8")
    .end(if (obj is String) obj else Json.encode(obj))
}

fun JsonObject.getOrDef(key: String, def: String) = this.getString(key) ?: def

inline fun  Iterable.forEachMultithreading(nThreads: Int = 5, crossinline funWorker: (T) -> Any?) {
  val coroutineDispatcher = Executors.newFixedThreadPool(nThreads).asCoroutineDispatcher()
  runBlocking {
    coroutineDispatcher.use {
      launch {
        forEachIndexed { index, arg ->
          // CoroutineContext coroutineDispatcher
          async(coroutineDispatcher) {
            funWorker(arg)
          }
        }
      }.join()
    }
  }
}

inline fun  Iterable.mapMultithreading(nThreads: Int = 5, crossinline funWorker: (T) -> Any?): Iterable {
  val results = arrayOfNulls(count())
  val coroutineDispatcher = Executors.newFixedThreadPool(nThreads).asCoroutineDispatcher()

  runBlocking {
    coroutineDispatcher.use {
      launch {
        forEachIndexed { index, arg ->
          // CoroutineContext coroutineDispatcher
          async(coroutineDispatcher) {
            funWorker(arg).let {
              results[index] = it
            }
          }
        }
      }.join()
    }
  }
  return results.asIterable()
}


InfixDemo.kt

package com.citi.ocean.ktdemo

import io.vertx.kotlin.core.json.json
import io.vertx.kotlin.core.json.obj

/**
 * @Author hw83770
 * @Date 11:53 2020/4/17
 *
 *
 * Kotlin: Improve readability by using the infix notation
 * https://www.deadcoderising.com/kotlin-improve-readability-by-using-the-infix-notation/
 *
 */
fun main() {

  val msg = json {
    obj(
      "timerId" to "123",
      "bool" to true,
      "num" to 1,
      "test1" to "test1"
    )
  }
  println(msg)

  // ---------------
  val map1 = mapOf(
    1 to "one",
    2.to("two"),
    Pair(3, "three")
//    new Pair(3, "three")
  )
  println(map1)

  val hashMap = hashMapOf(
    1 to "one",
    2 to "two",
    3 to "three"
  )
  println(hashMap)

  listOf(1, 2, 3, 4, 5) subtract listOf(2, 3)
  listOf(1, 2, 3, 4, 5) union listOf(6, 7)
  listOf(1, 2, 3, 4, 5) zip listOf(2, 3, 4, 5, 6)
  listOf(1, 2, 3, 4, 5) intersect listOf(2, 3)

  "Hello world" matches "\\w+\\s\\w+".toRegex()

  val randomNumbers = RandomNumbers(listOf(1, 2, 3, 4, 5, 6))
  randomNumbers take 3
}


class RandomNumbers(val list: List) {

  infix fun take(nrOfElements: Int): List {
    return list.shuffled().take(nrOfElements);
  }
}


DelegatesStudy.kt

package com.citi.ocean.ktdemo

import kotlin.properties.Delegates
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

/**
 * @Author hw83770
 * @Date 12:00 2019/8/29
 *
 */

class Raindy {
  val weather by lazy(LazyThreadSafetyMode.PUBLICATION) { "Raindy" }
  var name by PringDelegate()
}

class User(map: Map) {
  val name: String by map
  val age: Int by map
}

// 自定义 delegates, 将一些操作封装成一个属性,例如将Raindy的 value 属性设置成一个文件,
// 那么Raindy name set get操作都会是一个文件的 读写
class PringDelegate : ReadWriteProperty {

  private var value: String? = null
  override fun getValue(thisRef: Any, property: KProperty<*>): String {
    println("getValue: $thisRef -> ${property.name} ${property.returnType} $value")
    return value ?: ""
  }

  override fun setValue(thisRef: Any, property: KProperty<*>, value: String) {
    println("setValue: $thisRef -> ${property.name} = $value")
    this.value = value
  }
}

fun main() {
  var name by Delegates.observable(initialValue = "") { prop, old, new ->
    println("old val: $old, new val: $new")
  }
  name = "d"
  name = "a"
//  println("current name is $name")

  // ----------------
  var name2: String by Delegates.vetoable(initialValue = "test name2") { _, oldValue, newValue ->
    println("old val: $oldValue, new val: $newValue")
    return@vetoable newValue.contains("1")
  }
  name2 = "data1"
  name2 = "data2"
//  println("current name is $name2")

  var name3: String by Delegates.notNull()
//  name3 = "te"
//  println(name3)

  // -------------------
  val lazyData: Double by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
    println("Initializing lazyData")
    2.0
  }
//  println("--------")
//  println(lazyData)

  val userName = User(mapOf("name" to "ken", "age" to 20)).name
  println(userName)

//  val a = Raindy()
//  println(a.weather)
//  println(a.name)
//  a.name = "123"
//  println("now: " + a.name)


//  val b = BaseImpl(10)
//  Derived(b).print()
}

interface Base {
  fun print()
}

class BaseImpl(val x: Int) : Base {
  override fun print() {
    print(x)
  }
}

class Derived(b: Base) : Base by b


KotlinSTD.kt

package com.citi.ocean.ktdemo

/**
 * @Author hw83770
 * @Date 12:19 2020/4/17
 *
 */

// also
data class Person(var name: String) {
  var tutorial: String? = null
  var age: Int = 0
}

fun main() {

  val person = Person("ken").apply {
    age = 14
    tutorial = "kotlin"
  }
  println(person)

  val person2 = Person("ken2").let {
    it.age = 14
    it.tutorial = "java"
    return@let it
  }
  println(person2)

  // let -->  if not null
  val listWithNull = listOf("A", "S", null)
  println(listWithNull)
  for (item in listWithNull) {
    item?.let { print(it) }
  }

  val per: Person? = Person("ken")
  per?.let { person ->
    println(person.age)
    //    person.tutorial.substring(2)
    person.tutorial?.substring(2)
  }

  // null point
  var str: String? = "hellow fsdf"
  val len: Int? = str?.length
  println("length is $len")
}


BenchMarks.kt

package com.citi.ocean.ktdemo

import java.io.File
import java.util.concurrent.Semaphore

/**
 * @Author hw83770
 * @Date 10:26 2019/12/2
 *
 */

private val PRINT_REFIX = "[TimeTest]"


// sync funtion measureTime
fun measureTime(tag: String, testCount: Int, warmCount: Int, block: () -> Unit) {

  println("$PRINT_REFIX $tag =======  start")
  // warm up
  for (i in 0 until warmCount) {
    block()
  }
  println("$PRINT_REFIX $tag =======  warm done")

  // testing
  val startTime = System.currentTimeMillis()
  for (i in 0 until testCount) {
    block()
  }
  val totalTime = System.currentTimeMillis() - startTime

  println("$PRINT_REFIX $tag ======= total time: ${totalTime}ms")
  println("$PRINT_REFIX $tag ======= average time: ${totalTime / testCount}ms")
}


// async funtion measureTime
fun measureTimeAsync(tag: String, testCount: Int, warmCount: Int, asyncBlock: (Semaphore) -> Unit) {

  println("$PRINT_REFIX $tag =======  start")

  // warm up
  val semaphoreWarm = Semaphore(0)
  for (i in 0 until warmCount) {
    asyncBlock(semaphoreWarm)
  }
  semaphoreWarm.acquire(warmCount)
  println("$PRINT_REFIX $tag =======  warm done")

  // testing
  val semaphoreTest = Semaphore(0)
  val startTime = System.currentTimeMillis()
  for (i in 0 until testCount) {
    asyncBlock(semaphoreTest)
  }
  semaphoreTest.acquire(testCount)
  val totalTime = System.currentTimeMillis() - startTime

  println("$PRINT_REFIX $tag ======= total ${totalTime}ms")
  println("$PRINT_REFIX $tag ======= average ${totalTime / testCount}ms")
}


fun main() {
  measureTime(tag = "fun execute", testCount = 3, warmCount = 3) { testFun() }
}

fun testFun() {
  var sum = 0
  val file = File("test.txt")
  repeat(times = 1000) {
    sum = sum + it
    file.writeText(text = "sum is $sum")
  }
}

你可能感兴趣的:(kotlin example)