Statistics
6
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2026-03-27

AuthorMoaml Mohmmed

Google promoted Kotlin as a first class language on its Java-based Android platform back in May. Since then, the whole development world has been wondering: what is this language? Kotlin has been around for a few years and has been running on production systems, after the languages 1.0 release in February 2016, for a year or so. The language has received a lot of praise and loving words from the developer community. It is a breath of fresh air, a good upgrade to systems running older versions of Java, and still somehow an old dog in a familiar playing field. What is Kotlin? What does it bring that the JVM doesn't already have? Kotlin vs. Java There are a few approaches we can take when introducing Kotlin. We can discuss it through Java, the language Kotlin needs to be based on due to its JVM runtime, or we can do it through Scala, the language Kotlin is heavily influenced by. There is no doubt that Kotlin is better than Java. It is much safer and more concise. It provides you with a bunch of additions to your standard Java language and enhances a few bits and pieces that Java developers have grown to dislike. Additions include things like null safety, extension functions, data classes, objects, first class functions as well as extensive and expressive lambdas. Kotlin also enhances Java’s type inference and type system and takes massive leaps forward with collections. Kotlin vs. Scala Perhaps, it’s better to compare Kotlin against Scala. This comparison might scare some of you quite a bit because Scala has the reputation of being simultaneously intriguing and frightening. It heavily introduces functional programming paradigm to you while still mixing it into familiar object orientation (hence in an awfully lot of cases creating a mishmash of advanced techniques from both paradigms), brings in some new build tools, and gives your internal flow state a frustrating break every now and then due to long compile times. I come bearing both good news and bad news. Let’s star

Tags
No tags
ISBN: B08B9RKL74
Publisher: Mem lnc
Publish Year: 2020
Language: 英文
Pages: 176
File Format: PDF
File Size: 519.0 KB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

(This page has no text content)
kotlin The Ultimate Beginner's Guide to Learn kotlin Programming Step by Step 2020 Moaml mohmmed
2nd edition
Mem lnc
Introduction Kotlin is the new lovechild of the JVM developers' world. Google promoted Kotlin as a first class language on its Java-based Android platform back in May. Since then, the whole development world has been wondering: what is this language? Kotlin has been around for a few years and has been running on production systems, after the languages 1.0 release in February 2016, for a year or so. The language has received a lot of praise and loving words from the developer community. It is a breath of fresh air, a good upgrade to systems running older versions of Java, and still somehow an old dog in a familiar playing field. What is Kotlin? What does it bring that the JVM doesn't already have?
Kotlin vs. Java There are a few approaches we can take when introducing Kotlin. We can discuss it through Java, the language Kotlin needs to be based on due to its JVM runtime, or we can do it through Scala, the language Kotlin is heavily influenced by. There is no doubt that Kotlin is better than Java. It is much safer and more concise. It provides you with a bunch of additions to your standard Java language and enhances a few bits and pieces that Java developers have grown to dislike. Additions include things like null safety, extension functions, data classes, objects, first class functions as well as extensive and expressive lambdas. Kotlin also enhances Java’s type inference and type system and takes massive leaps forward with collections.
Kotlin vs. Scala Perhaps, it’s better to compare Kotlin against Scala. This comparison might scare some of you quite a bit because Scala has the reputation of being simultaneously intriguing and frightening. It heavily introduces functional programming paradigm to you while still mixing it into familiar object orientation (hence in an awfully lot of cases creating a mishmash of advanced techniques from both paradigms), brings in some new build tools, and gives your internal flow state a frustrating break every now and then due to long compile times. I come bearing both good news and bad news. Let’s start with the bad news: Bad news is that Kotlin is similar to Scala, it follows the same path as Scala does The good news: luckily, it’s only slightly similar to Scala in every aspect.
Kotlin & Functional Programming Paradigm The functional programming paradigm is big part of Kotlin as well. Luckily, it doesn't go into the higher-kinded types, monadic do-continuations, or advanced type theory concepts that make you seek out Bartosz Milewski and his brilliant book on Category Theory. Kotlin introduces easy-to-use collection manipulation functions and functional pipelines for you. You will get your maps, filters, and folds, which in most cases are enough to get to the functional programming path. Java devs that have been lucky enough to jump into Java 8 (hugs and kisses to you Android and/or enterprise developers) will be familiar with the these basics and will feel right at home when they jump into Kotlin. They will also find conciseness and safety of better type system, which will spark their first crush towards the language. It is just so pretty and seamless to pipe these functions together and build a clean pipeline. And when you come back to it after a few weeks, you’ll still feel like you can somewhat understand it. Smiles all around.
Java and Kotlin (You can skip reading this section if you are a beginner) The question that may come to Java developers' minds is "What should I learn now?" There are a range of languages that deserve consideration, such as Clojure, Rust or Haskell. But what if you want to learn something that helps you pay bills and is so easy to use? Kotlin may be your best choice, and we will try in this article to explain why. Java and Kotlin and difference between them A programming language developed by JetBrains, who were behind the IDEA idea as well as other things. A simple and flexible alternative to Java Matches well with the existing Java code Translate to Java bytecode Works on JVM It also translates to JavaScript If you have read its documents, you will notice a number of important things: Allows you to do a lot of things with a few codes Many of the problems in Java are solved
Help you continue to use the usual ecosystem of Java Allows you to program the front and back interface in the same language 100% compatible with Java They perform well compared to alternatives (Clojure, Scala) Add only a thin layer of complexity to Java Sounds good, does not it? Here are some examples to compare with Java. Elements of values versus data of items What you see here is an old Java object (POJO) with the usual patterns: public class HexagonValueObject { private final int x; private final int y; private final int z; public HexagonValueObject (int x, int y, int z) { this.x = x; this.y = y; this.z = z; }
public int getX () { return x; } public int getY () { return y; } public int getZ () { return z; } @Override public boolean equals (Object o) { if (this == o) return true; if (o = null | getClass ()! = o.getClass ()) return false; HexagonValueObject hexagon = (HexagonValueObject) o; return getX () == hexagon.getX () && getY () == hexagon.getY () && getZ () == hexagon.getZ (); }
@Override public int hashCode () { return Objects.hash (getX (), getY (), getZ ()); } @Override public String toString () { return "HexagonValueObject {" + "x =" + x + ", y =" + y + ", z =" + z + '}'; } Creating value elements is a cumbersome process even using libraries like Lombok) Lombok requires an attached installation in your IDE environment to work, which may not be possible in all development environments. This problem can be overcome with tools such as Delombok, Solution to the problem), at least IDEA (or Eclipse) gives you some help in generating a lot of those functions, but adding a field and forgetting the adjustment of the equals function will result in bad surprises. Let's now look at the corresponding code in Kotlin: data class HexagonDataClass (val x: Int, val y: Int, val z: Int) just awesome! We've shortened a lot of writing compared to the Java version. Data items in Kotlin give you
equals + hashCode and toString Plus Outcomes and setters. You can also copy them, creating a new object with some rewriting fields. Stratification of text strings String interpolation Dealing with text strings in Java is cumbersome. But can be simplified using String.format however will remain ugly. public class JavaUser { private final String name; private final int age; public String toHumanReadableFormat () { return "JavaUser {" + "name = '" + name +' \ '' + ", age =" + age + " '}'; } public String toHumanReadableFormatWithStringFormat () { return String.format ("JavaUser {name = '% s', age =% s}", name, age); } }
Kotlin found a solution to this, adding the concept of string filler, which extended the use of variables in literal strings. It was also possible to call jobs from them! class KotlinUser (val name: String, val age: Int) { fun toHumanReadableFormat () = "JavaUser {name = '$ name', age = $ age}" fun toHumanReadableFormatWithMethodCall () = "JavaUser {name = '$ {name.capitalize ()}', age = $ age}" } Extension functions Writing servers in Java decorators can be difficult, as they are not ideal. If you want to write a library, which can be used with all the categories that List offers, you can not simply use it in your server because it will need you to provide many other functions, so you will have to extend the AbstractList. public class ListPresenterDecorator <T> extends AbstractList <T> { private List <T> list; public ListPresenterDecorator (List <T> list) { this.list = list; }
public String present () { return list.stream () .map (Object :: toString) .collect (Collectors.joining (",")); } @Override public T get (int index) { return list.get (index); } @Override public int size () { return list.size (); } } Chapter II Data Types in Kotlin Every element in Kotlin is an object, since member functions and properties can be called over any variable, and some have their own internal representation; for example, boolean is represented as basic values during runtime ) But for the user just ordinary varieties. This page discusses the
main types of data in Kotlin: numbers, chars, boolean, arrays, and text strings. Numbers Kotlin uses numerical data in a similar way to Java but with simple differences. For example, Kotlin does not support implicit (from the smallest to widening) and the literals differ in some cases. Kotlin provides the following basic types of expression (similar to Java):
The characters are not numbers in Kotlin. Directal Constants It has the following types of integers: Decimals: 123 The long decimal numbers are characterized by the letter L (in its large case only) to form: 123L * Hexadecimal numbers such as 0x0F * Binaries such as 0b00001011 Kotlin does not support eight octal values, but it supports the conventional notation of floating-point numbers: * Double (default) such as: 123.5 and 123.5e10 * Float type (f or F) such as: 123.5f * Underscore in Numeric Literals starting with version 1.1 Use the underscore to make it easier to read large numbers such as: val oneMillion = 1_000_000 val creditCardNumber = 1234_5678_9012_3456L val socialSecurityNumber = 999_99_9999L val hexBytes = 0xFF_EC_DE_5E
val bytes = 0b11010010_01101001_10010100_10010010 Representation The numbers are physically stored in the Java platform as basic types in the JVM unless there is a nullable reference to the number (eg Int?) Or the generics is not included, then the boxed numbers are not necessarily preserved and this does not necessarily preserve their identity, In the code: val a: Int = 10000 print (a === a) // will print true val boxedA: Int? = a val anotherBoxedA: Int? = a print (boxedA === anotherBoxedA) // will print false But it maintains the equal value (with the symbol ==): val a: Int = 10000 print (a == a) // will print true val boxedA: Int? = a val anotherBoxedA: Int? = a print (boxedA == anotherBoxedA) // also will print true Explicit Conversion
The smaller species in Kotlin are not subtypes of larger species due to the different methods of representing numerical data among them, but they will also cause the following problems: // This is a fake code and will not work correctly val a: Int? = 1 // Envelope integer (java.lang.Integer) val b: Long? = a // An implicit conversion that results in an envelope type type Long (java.lang.Long) print (a == b) // This will result in a false result The reason for the appearance of a false result in the last line of the previous code is that the equals function realizes that the other variable is also of the Long type. This is not true. Thus, we have not only lost identity, but also equality, And therefore a Byte value, for example, can not be assigned to a value of Int type without declaring that conversion, such as: val b: Byte = 1 // No problem here val i: Int = b // False attribution By adding the explicit conversion, the code becomes: val i: Int = b.toInt () // An explicit conversion of the smallest type to the largest type Any of the following conversions can be used: toByte (): Convert to Byte type toShort (): Convert to Short type
toInt (): Converts to type Int toLong (): Convert to Long type toFloat (): Convert to Float type toDouble (): Convert to Double Type toChar (): Convert to Char type The absence of implicit conversions is not a problem; because the type guesses through the context, as well as the overloading of arithmetical operations in line with the most appropriate conversion, such as: val l = 1L + 3 // Long + Int => Long