most from reference

一些常用操作

创建单例类 object 数据类data class
List、Map、Array的简单操作
Lazy延迟加载属性
空类型?
空类型表达式?.、?:、?.let{}
try catch finally语句块 
无参函数表示一个值
条件判断语句 if else 及 when else 
with语句块
IO流操作并使用lambda表达式
函数声明时直接内联一个其它方法,相当于其方法实现 inline 
类Java的void类型:Unit

package com.jackie.basic

import java.io.File
import java.nio.file.Files
import java.nio.file.Paths

/**
 * Created by Jackie on 2017/7/28.
 * Idioms
 * A collection of random and frequently used idioms in Kotlin.
 * If you have a favorite idiom, contribute it by sending a pull request.
 */
class Idioms {
}

/**
 *Create DTOs(POJOs/POCOs)
 * Provides a Customer class with the following functionality:
 *   getters (and setters in case of vars) for all properties
 *   equals()
 *   hashCode()
 *   toString()
 *   copy()
 *   component1(), component2(), …, for all properties (see Data classes)
 */
data class Customer(val name: String, val email: String) //数据类的属性必须用val(不可变)或者var(可变)来修饰 属性无法修改
data class User(var name: String = "", val email: String = "") //为属性添加默认值  之后创建对象时,就可以不输或少输构造方法参数

//Creating a singleton
object Resource {
    val name = "Name"
}

fun main(args: Array<String>) {
    var customer = Customer("Jackie", "717702148@qq.com")
//    customer.name = "Jack"  //var couldn't be modified

    var list1 = listOf(-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5)
    //Filtering a list
    var positives = list1.filter { x -> x > 0 }
    //Or alternatively, even shorter:
//    val positives = list1.filter { it > 0 }

    println(positives)

    //Traversing a map/list of pairs
    var map1 = HashMap<Int, String>()
    map1[0] = "Good"; map1[1] = "Good"; map1[2] = "Study"
    map1[3] = "Day"; map1[4] = "Day"; map1[5] = "Up"

    for ((key, value) in map1) {
        println("$key -> $value")
    }

    //key, value can be called anything.

    //Using ranges
    for (i in 1..100) {
    }  // closed range: includes 100
    for (i in 1 until 100) {
    } // half-open range: does not include 100
    for (x in 2..10 step 2) {
    }

//    for (x in 10 downTo 1) {
//        if (x in 5..8) {
////            print(x + " ")  //x是Int 编译报错 同 var result = 5 + " "
////            print(" " + x)  //编译通过
//            print(x.toString() + " ")
//        }
//    }

    //上面的简写
    (10 downTo 1)
            .filter { it in 5..8 }  //it是固定命名,表示Int
            .forEach { print(it.toString() + " ") }

    println()

    //Read-only list
    val list2 = listOf("a", "b", "c")
    for (list in list2) {
        println(list)
    }

    //按index打印
    for ((i, e) in list2.withIndex()) {
        println("$i $e")
    }

    //Read-only map
    val map2 = mapOf(0 to "Good", 1 to "Good", 2 to "Study", 3 to "Day", 4 to "Day", 5 to "Up")
    //Accessing a map
    println(map2[0])

    for (key in map2.values) {
        print(key + " ")
    }

    println()

    //Lazy property
    fun lazy() {
        val p: String by lazy {
            println("in this")
            var a = "aa"  //do something
            "aaa" //最后必须给lazy属性赋值  之前可做些其它事
        }

        println("lazy value p = $p")
    }

    lazy()

    //Extension Functions
    fun String.convertToUpperCase(): String {  //为String 添加扩展函数,把字符串转为大写字母
        return this.toUpperCase()  //任何字符串都可以调用这个扩展函数,this指接收者对象(Receiver Object)(也就是调用扩展函数时, 在"."号之前指定的对象实例).
    }

    print("Convert this to uppercase".convertToUpperCase())

//    fun Activity.toast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT) {
  //为Activity 添加扩展函数
//        Toast.makeText(this, message, duration)
.show()
//    }

    println()

    //If not null shorthand
    val files1 = File("Test").listFiles()
    println(files1?.size)  //可以为null

    //If not null and else shorthand
    //使用Elvis操作符来给定一个在是null的情况下的替代值
    val files2 = File("Test").listFiles()
    println(files2?.size ?: "empty")

    //Executing a statement if null
    val data = mapOf("email" to null)
//    val email = data["email"] ?: throw IllegalStateException("Email is missing!")

    //Execute if not null
    data?.let {
        // execute this block if not null
        println("data is not null")
    }

    //Map nullable value if not null
//    val mapped = data?.let { transformData(it) } ?: defaultValueIfDataIsNull

    fun transform1(color: String): Int {
        return when (color) {
            "Red" -> 0
            "Green" -> 1
            "Blue" -> 2
            else -> throw IllegalArgumentException("Invalid color param value")
        }
    }

    //'try/catch' expression
    fun test() {
        val result = try {
//            count()
        } catch (e: ArithmeticException) {
            throw IllegalStateException(e)
        }

        // Working with result
    }

    //'if' expression
    fun foo(param: Int) {
        val result = if (param == 1) {
            "one"
        } else if (param == 2) {
            "two"
        } else {
            "three"
        }
    }

    //Builder-style usage of methods that return Unit
    fun arrayOfMinusOnes(size: Int): IntArray {
        return IntArray(size).apply { fill(10) } //生成一个size长度的int数组,每个索引都填充成10
    }

    print(arrayOfMinusOnes(5).filter { it > 5 }.forEach { println(it) })

    //Single-expression functions
    fun theAnswer1() = 42

    //This is equivalent to
    fun theAnswer2(): Int {
        return 42
    }

    //This can be effectively combined with other idioms, leading to shorter code. E.g. with the when-expression:
    fun transform2(color: String): Int = when (color) {
        "Red" -> 0
        "Green" -> 1
        "Blue" -> 2
        else -> throw IllegalArgumentException("Invalid color param value")
    }

    //Calling multiple methods on an object instance ('with')
    fun withObject(obj: Idioms) {
        //使用with(object) ,在block中 可直接调用 对象实例的 fun, 不需要obj.前缀
        with(obj) {
            foo(2)
        }
    }

    //Java 7's try with resources
//    val stream = Files.newInputStream(Paths.get("/some/file.txt"))
//    stream.buffered().reader().use { reader ->
//        println(reader.readText())
//    }

    //Convenient form for a generic function that requires the generic type information

//  public final class Gson {
//     ...
//     public <T> T fromJson(JsonElement json, Class<T> classOfT) throws JsonSyntaxException {
//     ...

    //    private fun <T: Any> fromJson(str: String, clazz: Class<T>) {
    /*private*/ fun <T> fromJson(str: String, clazz: Class<T>): T? {
        return null
    }

    /*
    inline 内联一个方法, 前面为fun定义,且使用了泛型,后面直接 = 内联的方法
     */
//    inline fun <reified T: Any> Gson.fromJson(json: JsonElement): T = this.fromJson(json, T::class.java)

    //Consuming a nullable Boolean
//    val b: Boolean = false
    var b: Boolean? = false
    if (b == true) { //Boolean?的比较,不能省略 ==
        // 'b' is true
    } else {
        // 'b' is false or null
    }
}

Kotlin Reference (二) Idioms的更多相关文章

  1. 浅谈Kotlin(二):基本类型、基本语法、代码风格

    浅谈Kotlin(一):简介及Android Studio中配置 浅谈Kotlin(二):基本类型.基本语法.代码风格 浅谈Kotlin(三):类 浅谈Kotlin(四):控制流 通过上面的文章,在A ...

  2. 【Kotlin】初识Kotlin(二)

    [Kotlin]初识Kotlin(二) 1.Kotlin的流程控制 流程控制是一门语言中最重要的部分之一,从最经典的if...else...,到之后的switch,再到循环控制的for循环和while ...

  3. Kotlin Reference (十二) Extensions

    most from reference Kotlin与C#和Gosu类似,提供了扩展一个新功能的类,而不必继承类或使用任何类型的设计模式,如Decorator(装饰者模式).这是通过称为扩展的特殊声明 ...

  4. Kotlin Reference (十一) Visibility Modifiers

    most from reference 类,对象,接口,构造函数,函数,属性及setters具有可见性修饰符(getter总是具有和属性一样的可见性).在kotlin中油4个可视化修饰符:privat ...

  5. Kotlin Reference (十) Interfaces

    most from reference 接口 Kotlin中的接口非常类似于Java8,它们可以包含抽象方法的声明以及方法实现.与抽象类不同的是接口不能存储状态.它们可以具有属性,但这些需要是抽象的或 ...

  6. Kotlin Reference (九) Properties and Fields

    most from reference 声明属性 Koltin的类都有属性,这些属性可以声明为可变的,使用var关键字或用val关键字生声明不可变属性. class Address { var nam ...

  7. Kotlin Reference (八) Classes and Objects

    most from reference 类 Kotlin的类的声明使用关键字class class Invoice { } 类声明由类名.类头(指定其类型参数,构造函数等)和类体组成,由大括号括起来. ...

  8. Kotlin Reference (七) Returns and Jumps

    most from reference kotlin有三个结构跳跃表达式 return 默认情况下,从最近的封闭函数或匿名函数返回. break 跳出整个循环 continue 跳出本次循环,进行下一 ...

  9. Kotlin Reference (六) Control Flow

    most from reference if表达式 在kotlin中,if是一个表达式,即它返回一个值.kotlin中没有Java中的三元运算符. // Traditional usage var m ...

随机推荐

  1. Jquery8 基础事件

    学习要点: 1.绑定事件 2.简写事件 3.复合事件 JavaScript 有一个非常重要的功能,就是事件驱动.当页面完全加载后,用户通过鼠标或键盘触发页面中绑定事件的元素即可触发.jQuery 为开 ...

  2. Spring笔记(二)

    1. SPRING aop入门 Aop  面向切面编程 在一个大型的系统中,会写很多的业务类--业务方法 同时,一个大型的系统中,还有很多公共的功能:比如事务管理.日志处理.缓存处理..... 1.1 ...

  3. 在vim中的复制,剪切,粘贴

    1. 剪切和粘贴 定位鼠标到剪切的开始位置 输入v键开始选择剪切的字符,或者V键是为了选择 整行 移动方向键到结束的地方 d键是剪切,y键是复制 移动鼠标到粘贴的位置 输入P是在鼠标位置前粘贴,输入p ...

  4. poj-2259 team queue(数据结构)

    第一遍看的时候立即想到了哈希表. 再想时觉得两个队列,一个用来排队伍之间的顺序,一个用来排队伍内部成员的顺序即足够了. DEQUE的时候先判断哪只队伍排在队首,之后再让该队伍中的首队员出列. 整体没有 ...

  5. Basic Authentication in ASP.NET Web API

    Basic authentication is defined in RFC 2617, HTTP Authentication: Basic and Digest Access Authentica ...

  6. Permission denied: mod_fcgid

    [Tue Jun 16 13:29:08 2015] [warn] (13)Permission denied: mod_fcgid: spawn process /var/www/cgi-bin/g ...

  7. 远程线程注入shellcode笔记

    #include "stdafx.h" #include <windows.h> #include <stdio.h> char shellcode[] = ...

  8. Android -- 提交数据到服务器,Get Post方式, 异步Http框架提交

    1. 发送请求到服务器有几种方式 (1)HttpURLConnection (2)Httpclient 同步框架 (3)AsyncHttpClient 异步框架 (https://github.com ...

  9. 模仿某旅行网站 纯css实现背景放大效果

    基本功能是鼠标移动到图片上,对应宽度变宽.其中布局和基本样式直接copy官网,功能部分是自己瞎鼓捣实现的. 直接上代码: HTML部分 <div class="fold_wrap&qu ...

  10. Vuejs methods how to use

    <!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8&qu ...