Tuesday, May 29, 2018

Kotlin



https://kotlinlang.org/docs/tutorials/getting-started.html
kotlinc <source file or directory> -include-runtime -d <jar name>
The parameter type is written after its name

fun max(a: Int, b: Int): Int {
    return if (a > b) a else b
}
    println("Hello, ${if (args.size > 0) args[0] else "someone"}!")
class Person(val name: String)


https://dzone.com/articles/null-safe-programming-the-kotlin-way
By default, a reference of type String cannot hold null, whereas String? allows it. This distinction on its own doesn't make a very big difference, obviously. Therefore, whenever you choose to work with nullable types, the compiler forces you to handle possible issues, i.e. potential NPEs, appropriately.

var b: String? = “possiblyNull”
//1. does not compile, could throw NPE
val len = b.length
//2. Check nullability before access
if (b != null){
   b.length
}
//3. Use safe operator
val len = b?.length
As an alternative to explicit checks, the safe call operator ?. can be used. The expression b?.length can be translated to "call length on b if b is not null, otherwise return null." The return type of this expression is of type Int? because it may result in null. Chaining such calls is possible and very useful because it lets you safely omit a great number of explicit checks and makes the code much more readable:
person?.address?.city ?: throw IllegalStateException("No city associated to person.")

Another very useful operator is the elvis operator ?: that perfectly complements the safe call operator for handling else cases. If the left-hand expression is not null, the elvis operator returns it; otherwise, the right-hand expression will be called.
The last operator that you need to know is called not-null assertion operator !!. It converts any reference to a non-null type. This unchecked conversion may cause an NPE if that reference is null after all. The not-null assertion operator should only be used with care:
person!!.address!!.city //NPE will be thrown if person or address is null
https://allegro.tech/2018/05/From-Java-to-Kotlin-and-Back-Again.html
https://mp.weixin.qq.com/s/MXi0Uj94tOjjt7E2cNQy1Q
其次,一般来说,在查看一个方法的声明时,我们会先看方法名和返回类型,然后再查看参数。
而在 Kotlin 中,方法的返回类型可能远在行尾,所以需要滚动到最后面:
private fun getMetricValue(kafkaTemplate : KafkaTemplate<String, ByteArray>, metricName : String) : Double {
    ...
}

“好吧,但我需要 MyClass 的 logger 对象,我该怎么办?”
“没问题,你可以使用 Companion 对象。”
“什么是 Companion 对象?”
“它是与类绑定的单例对象,可以把你的 logger 放在 Companion 对象中。“Kotlin 解释说“我懂了,是这样吗?”
class MyClass {
    companion object {
        val logger = LoggerFactory.getLogger(MyClass::class.java)
    }
}


通过单例来声明对象的做法很管用,但是从语言中移除静态成员是不切实际的。在 Java 中,我们一直使用静态的 logger 对象。它只是一个 logger 而已,这个时候我们没有必要关心它是不是面向对象的,而且它并不会带来任何坏处。
有时候,我们必须使用 static,比如 public static void main() 仍然是启动 Java 应用程序的唯一方式。试着不使用谷歌搜索写出下面的 Companion 对象吧。
class AppRunner {
    companion object {
        @JvmStatic fun main(args: Array<String>) {
            SpringApplication.run(AppRunner::class.java, *args)
        }
    }
}

在 Kotlin 中,类默认是 final 的。如果想扩展一个类,必须添加 open 修饰符。
继承语法如下所示:
open class Base

class Derived : Base()
Kotlin 使用: 操作符代替 extends 关键字,还记得吗,这个操作符已经用于分隔变量名与类型。难道我们又回到了 C++ 语法?
颇具争议的是,在默认情况下,类是 final 的。但我们生活在一个满是框架的世界,而框架喜欢使用 AOP。 Spring 使用库(cglib、jassist)为 bean 生成动态代理,Hibernate 通过扩展实体类来实现延迟加载。
如果你使用 Spring,那么就有两种选择。你可以在所有的 bean 类前面加上 open(这很枯燥),或者使用这个编译器插件:
buildscript {
    dependencies {
        classpath group: 'org.jetbrains.kotlin', name: 'kotlin-allopen', version: "$versions.kotlin"
    }
}


Labels

Review (572) System Design (334) System Design - Review (198) Java (189) Coding (75) Interview-System Design (65) Interview (63) Book Notes (59) Coding - Review (59) to-do (45) Linux (43) Knowledge (39) Interview-Java (35) Knowledge - Review (32) Database (31) Design Patterns (31) Big Data (29) Product Architecture (28) MultiThread (27) Soft Skills (27) Concurrency (26) Cracking Code Interview (26) Miscs (25) Distributed (24) OOD Design (24) Google (23) Career (22) Interview - Review (21) Java - Code (21) Operating System (21) Interview Q&A (20) System Design - Practice (20) Tips (19) Algorithm (17) Company - Facebook (17) Security (17) How to Ace Interview (16) Brain Teaser (14) Linux - Shell (14) Redis (14) Testing (14) Tools (14) Code Quality (13) Search (13) Spark (13) Spring (13) Company - LinkedIn (12) How to (12) Interview-Database (12) Interview-Operating System (12) Solr (12) Architecture Principles (11) Resource (10) Amazon (9) Cache (9) Git (9) Interview - MultiThread (9) Scalability (9) Trouble Shooting (9) Web Dev (9) Architecture Model (8) Better Programmer (8) Cassandra (8) Company - Uber (8) Java67 (8) Math (8) OO Design principles (8) SOLID (8) Design (7) Interview Corner (7) JVM (7) Java Basics (7) Kafka (7) Mac (7) Machine Learning (7) NoSQL (7) C++ (6) Chrome (6) File System (6) Highscalability (6) How to Better (6) Network (6) Restful (6) CareerCup (5) Code Review (5) Hash (5) How to Interview (5) JDK Source Code (5) JavaScript (5) Leetcode (5) Must Known (5) Python (5)

Popular Posts