为什么选择Kotlin?

Google在Google I/O上宣布正式支持Kotlin语言了,这是一门运行在JVM之上的强类型语言,有很强的类型推导能力,可以复用已有的Java库,工业级的面向对象语言。
展开查看详情

1.The case for Kotlin Barry Feigenbaum, Ph.D. 03/27/2018 Copyright © Barry Feigenbaum. All rights Reserved Bye Java! Hello Kotlin !

2.Presenter: Barry Feigenbaum, Ph. D. Sr. Principal SW Engineer at Dell Enterprise Currently working on storage management solutions Greater than 30 years of SW development experience Developer, Architect, Manager, Evangelist, etc. Working with Java since near day one (stated with 1.0.2) Oracle Certified Also C/C++, C#, Python and several other languages Adjunct Professor at ACC; past at St. Edwards and UT Author of multiple technical books and articles

3.Topics Brief Kotlin Background Why Kotlin : What others in the community are saying Kotlin Feature Introduction/Tour Deeper Kotlin by Example Summary/Conclusion Questions? Note: most uncredited code samples included herein come from: https://compsciclub.ru/media/slides/csseminar_2011_autumn/2011_10_02_csseminar_2011_autumn.pdf They are a bit out of date but still informative.

4.Today Java is King of the JRE - but there are heirs apparent Java usage is widespread but declining over time Why: Language is too verbose and lacks important modern language features Java 8 ** (lambdas, etc.) was a major step forward, but still not enough JCP process cannot keep up with demand for new features Some level of resistance to extending Java (if not a “perfect” enhancement) Several JVM languages attempt to overcome these missing features Scala, Groovy, Jython , JRuby , Clojure, Kotlin , etc. JRE (not a particular language) is the primary compatibility point Kotlin is a well thought out compromise/union among competitors Strongly endorsed (by Google) Good pedigree (JetBrains) Rapidly gaining in popularity Interests entry programmers/schools Announcement of Kotlin Support at Google IO 2017 ** Java 9 and 10 help a bit more.

5.What is Kotlin Kotlin  is a  statically typed   programming language  that runs on the  Java virtual machine and also can be compiled to  JavaScript  source code or use the  LLVM  compiler infrastructure. While the syntax is not compatible with Java, Kotlin is designed to interoperate with  Java  code and is reliant on Java code from the existing  Java Class Library , such as the  collections framework . Kotlin uses aggressive  type inference   to determine the type of values and expressions for which type has been left unstated. This reduces language verbosity relative to Java, which demands often entirely redundant type specifications. Kotlin is designed to be an industrial-strength  object-oriented  language , and a "better language" than Java , but still be fully interoperable with Java code, allowing companies to make a gradual migration from Java to Kotlin . In addition to the  classes  and  methods  (called member functions in Kotlin ) of  object-oriented programming , Kotlin also supports  procedural programming  with the use of  functions . https://en.wikipedia.org/wiki/Kotlin_(programming_language)

6.Kotlin Background A relatively new (since 2011) language for Java Runtime Environment (JRE) Combines many “best” features of predecessors : Java, C#, Groovy, Scala, Ruby, and several others Adds significant programmer efficiency and runtime safety vs. Java A language comparable to C# in flexibility and power Fully interoperable with Java code (call/return; interchangeable data types) Grew up in Android world Trends show it supplanting Java as the preferred Android language Formally endorsed by Google (Android owner) Usage is spreading beyond Android Free and Open Source https://kotlinlang.org/ ; https://www.jetbrains.com/ ; https://www.jetbrains.com/idea/?fromMenu ;

7.Excellent Kotlin IDE Support Available Critical to attract Developers IDEA has Kotlin built-in Eclipse supported via plug-in

8.What others say about Kotlin Summary: Kotlin is Well Received

9.What others say about Kotlin - Heroku It’s rare when a highly structured language with fairly strict syntax sparks emotions of joy and delight . Kotlin , which is statically typed and compiled like other less friendly languages, delivers a developer experience that thousands of mobile and web programmers are falling in love with . The first thing you’ll notice about Kotlin is how streamlined it is compared to Java. We need Kotlin as an alternative to Java just as we needed Java as an alternative to C 20 years ago. Kotlin has learned from the JVM languages that preceded it and borrowed the best parts from those ecosystems. The result is a well rounded, powerful, and production-ready platform for your apps. https://blog.heroku.com/rise-of-kotlin

10.What others say about Kotlin - Spring Kotlin is a statically typed language , but thanks to its  clever type inference , it allows you to write code as short and expressive as dynamic language with performances close to pure Java projects Properties support Relatively lightweight standard library compared to other languages Easy to learn : a Java developer can quickly understand most of the language (this  quick comparison to Java  is worth to read) Java interop  is a first class concern and great Built-in immutability and  null safety  support Code is easy to read, efficient to write ; No semicolon required ;-) Allows one to   extend existing libraries   without having to inherit from the class or use any type of design pattern such as Decorator https://spring.io/blog/2016/02/15/developing-spring-boot-applications-with-kotlin

11.What others say about Kotlin - Expedia What we like: Seamless interoperation with Java allows us to slowly migrate to Kotlin without having to throw away all of our current, working code . Converting to Kotlin has been fairly painless , thanks to functionality built into the Kotlin plugin for IntelliJ that automatically converts Java code to Kotlin . The explicit handling of null in Kotlin has helped us to dramatically reduce the number of dreaded NullPointerExceptions encountered by our users in the wild. Extension functions have allowed us to add functionality to platform classes , allowing for a more natural coding style and eliminating the need to create utility classes. Kotlin makes it easy to write less boilerplate and more concise code , so we can spend more time working on real functionality and finding and understanding the functionality becomes easier…. The data class is an excellent example of this. The Kotlin functional programming style operators , especially for dealing with collections . There are still a few places where Kotlin falls short of Java: No support among static code analysis  tools (e.g. Fortify, SonarQube , etc.) means we lose out on the types of automated feedback these tools provide . https://techblog.expedia.com/2017/05/18/learnings-from-two-years-of-kotlin/

12.Brief tour of Kotlin By no means covering all of Kotlin’s features

13.Hello World! package org.kotlin.byexample // 1 fun main( args : Array<String>) { // 2 println ("Hello, World!") // 3 } Kotlin code is defined in packages. Like with Java, if you don’t define one, the default package will be used The main entry point to a Kotlin application is a function called main println writes to standard output; it is implicitly imported http://kotlinbyexample.org/examples/helloWorld Note Kotlin uses type after name (vs. type before name as C derived languages do, such as Java) style Where is the class definition? In Kotlin its not needed for top level static functions. Wrapping class generated from source file name. package org.baf.hello ; public class HelloWorld { public static final void main(String[] args ) { System. out .println ( "Hello, World!" ); } } Java Form: Kotlin is briefer

14.Kotlin Base Types (all are reference types) (act as Java primitive equivalents) Numeric Types Other types Char 16 Boolean Array String https://kotlinlang.org/docs/reference/basic-types.html Type Bit width Double 64 Float 32 Long 64 Int 32 Short 16 Byte 8 Types have more function than Java primitives or primitive wrappers Long/raw (ex. Reg ex) strings: val text = """ |Tell me and I forget. |Teach me and I remember. |Involve me and I learn. |(Benjamin Franklin) """. trimMargin ()

15.Special Types Different syntax, similar meaning Nullable , function and tuple types are not in Java ( Optional is weak replacement for nullable type) Special Reference Types Any? : Root type (similar to Java’s Object ) but works better with generics Nothing : like Java’s null but is a type Unit : useful to declare the equivalent of void methods; assumed if a function has no return type

16.Kotlin Reserved Words Kotlin Operators Kotlin keywords List as break class continue do else false for fun if in interface is null object package return super this throw true try typealias typeof val var when while     These keywords are called hard keywords; !xxx and xxx? for some reserved Several soft (context) keyword exist https://kotlinlang.org/docs/reference/keyword-reference.html ; grammar.html Reserved for future Similar to Java Sameness: ===, !==

17.Kotlin Packages/Imports Packages/Imports work much like in Java but enhanced. package foo.bar import foo.Bar // Bar accessible unqualified import foo .* // all public in package foo accessible import bar.Bar as bBar // bBar stands for bar.Bar The  import  keyword is not restricted to importing classes; you can also use it to import other declarations: top-level functions and properties functions and properties declared in  object declarations enum constants https ://https://kotlinlang.org/docs/reference/packages.html A number of packages are imported into every Kotlin file by default: kotlin.* kotlin.annotation.* kotlin.collections.* kotlin.comparisons.*   kotlin.io.* kotlin.ranges.* kotlin.sequences.* kotlin.text .* java.lang.* kotlin.jvm .* / kotlin.js.*

18.Kotlin Type Aliases Type aliases provide alternative (generally shorter) names for existing types. typealias NodeSet = Set< Network.Node > typealias FileTable <K> = MutableMap <K, MutableList <File>> typealias MyHandler = ( Int , String, Any) -> Unit typealias Predicate<T> = (T) -> Boolean class A { inner class Inner } class B { inner class Inner } typealias AInner = A.Inner typealias BInner = B.Inner https://kotlinlang.org/docs/reference/type-aliases.html Type aliases are like macros, they do not introduce new types. They are equivalent to the corresponding underlying types. For example, when you add typealias Predicate<T>  and use  Predicate< Int >  in your code, the Kotlin compiler always expand it to  ( Int ) -> Boolean . Thus you can pass a variable of your type whenever a general function type is required and vice versa

19.Kotlin Variable/Field Declarations Kotlin has powerful type inference. Kotlin does not enforce immutability but it is recommended. In essence, prefer val over var . var a: String = "initial" // 1 val b: Int = 1 // 2 ​ val const = 3 // 3 var e: Int // 1 println (e) // 2 Declare a mutable variable and initialize it Declare an immutable variable and initialize it Declare an immutable variable and initialize it. The compiler infers the type (as Int ). Declare a mutable variable, but don’t initialize it. Produces compiler error: Variable ‘e’ must be initialized http://kotlinbyexample.org/examples/variables

20.String Templates val greeting = " Kotliner " println ("Hello $greeting") // 1 println ("Hello ${ greeting.toUpperCase ()}") // 2 Strings  in Kotlin can include references to variables that are interpolated C an include any expression enclosed in curly braces Generally easier to use than String.format http://kotlinbyexample.org/examples/stringTemplates

21.String Templates val greeting = " Kotliner " println ("Hello $greeting") // 1 println ("Hello ${ greeting.toUpperCase ()}") // 2 Strings  in Kotlin can include references to variables that are interpolated C an include any expression enclosed in curly braces Generally easier to use than String.format http://kotlinbyexample.org/examples/stringTemplates

22.Working with Nulls fun describeString ( maybeString : String ? ): String { // 1 if ( maybeString != null && maybeString.length > 0) { // 2 return "String of length ${ maybeString.length }" } else { return "Empty or null string" } } A function that takes in a nullable String and gives you a phrase describing it If the given String is not null and not empty, tell the caller about it’s length http://kotlinbyexample.org/examples/nullSafety Note “?” which says type is “nullable” (can be null) Null test needed only because type is nullable; Remove ? and variable cannot be null – checked by compiler

23.If/Else as Expression ; Expression Function fun describeString ( maybeString : String): String = if ( maybeString.length > 0) "String of length ${ maybeString.length }" else "Empty string" http://kotlinbyexample.org/examples/nullSafety Note no null test needed If/Else, When, Try/Catch are expressions in Kotlin

24.As Casts – “unsafe” casts; Is Tests val x: String = y as String // 1 val x: String? = y as String? // 2 val x: String? = y as ? String // 3 if (something is List<*>) { // 4 something.forEach { println (it) } // “it” is typed Any? } Exception if cannot cast; type wrong or value is null Exception if cannot cast; type wrong No exception will be thrown; if cannot cast result is null Cannot cast to specific generic type (due to type erasure) so use wild card https://kotlinlang.org/docs/reference/typecasts.html

25.As Casts – “unsafe” casts; Is Tests val x: String = y as String // 1 val x: String? = y as String? // 2 val x: String? = y as ? String // 3 if (something is List<*>) { // 4 something.forEach { println (it) } // “it” is typed Any? } Exception if cannot cast; type wrong or value is null Exception if cannot cast; type wrong No exception will be thrown; if cannot cast result is null Cannot cast to specific generic type (due to type erasure) so use wild card https://kotlinlang.org/docs/reference/typecasts.html

26.As Casts – “unsafe” casts; Is Tests val x: String = y as String // 1 val x: String? = y as String? // 2 val x: String? = y as ? String // 3 if (something is List<*>) { // 4 something.forEach { println (it) } // “it” is typed Any? } Exception if cannot cast; type wrong or value is null Exception if cannot cast; type wrong No exception will be thrown; if cannot cast result is null Cannot cast to specific generic type (due to type erasure) so use wild card https://kotlinlang.org/docs/reference/typecasts.html

27.While/Do Loops fun main( args : Array<String>) { var cakesEaten = 0 var cakesBaked = 0 while ( cakesEaten < 10) { // 1 eatACake () cakesEaten ++ } do { // 2 bakeACake () cakesBaked ++ } while ( cakesBaked < cakesEaten ) } While and do-while constructs work similarly to most languages. Performs the block while the condition is false Performs the block first, and then loops while evaluating the while condition. http://kotlinbyexample.org/examples/loops Continue/Break like in Java

28.Kotlin Collections val numbers: MutableList < Int > = mutableListOf (1, 2, 3) val readOnlyView : List< Int > = numbers // immutable println (numbers) // prints "[1, 2, 3]" numbers.add (4) println ( readOnlyView ) // prints "[1, 2, 3, 4]" readOnlyView.clear () // -> does not compile val strings = hashSetOf ("a", "b", "c", "c") assert( strings.size == 3) val items = listOf (1, 2, 3) https://kotlinlang.org/docs/reference/collections.html Unlike many languages, Kotlin distinguishes between mutable and immutable collections (lists, sets, maps, etc ). 

29.Kotlin Collections ( cont ) val readWriteMap = hashMapOf ("foo" to 1, "bar" to 2) println ( readWriteMap ["foo"]) val snapshot: Map<String, Int > = HashMap ( readWriteMap ) val items = listOf (1, 2, 3, 4) items.first () == 1; items.last () == 4 // both true items.filter { it % 2 == 0 } // returns [2, 4] val rwList = mutableListOf (1, 2, 3) rwList.requireNoNulls () // returns [1, 2, 3] if ( rwList.none { it > 6 }) println ("No items above 6") val item = rwList.firstOrNull () https://kotlinlang.org/docs/reference/collections.html There are various useful extension methods on collections that are worth being familiar with. Note operator overloading of […] Note map item pair literals using “to”