[JAVA] Kotlin 1.3.50 has been released !!

https___qiita-image-store.s3.amazonaws.com_0_79387_fcbcb29e-7cfd-9fb6-d0d1-02a1dd256a4c.png https://kotlinlang.org/

2019/8/22 Kotlin 1.3.50 has been released: tada :: tada :: tada: Kotlin 1.3.50 released

together Kotlin coroutiees1.3.0 has also been released! (I won't touch this one this time ..)

Kotlin Fest 2019 was also released just before the event! (Those who took the stage had a hard time correcting the materials to correspond to 1.3.50 just before ..)

I translated the release blog abbreviated below. I'm not very used to it so I'm sorry if there is a mistranslation: bow:

: star2: Summary

--The mechanism of Null-Check has been optimized. --A new Duration and time measurement API has been implemented (available in preview) --Improved Java-to-Kotlin converter --As an Experimental, in Gradle Kotlin / JS projects, you can now declare npm dependency resolution to the outside using Dukat. --A plugin for Kotlin / Native debugging for IntelliJ IDEA Ultimate --Support for Java compilation in multi-platform projects

Null-check optimization for Kotlin 1.4

Kotlin reduces the possibility of NullPointerExceptions by supporting nullable types, but it is impossible to avoid NPE altogether due to its interoperability with Java code. To help developers better understand the cause of the null possibility, the Kotlin compiler throws various types of runtime exceptions with explicit error messages instead of pure NPE. This approach turned out to be problematic. It interferes with the optimization of null checks that may be performed by either the Kotlin compiler or any of the various types of bytecode processing tools such as the Android R8 Optimizer.

To resolve this, starting with Kotlin 1.4, all runtime null checks throw java.lang.NullPointerException instead of KotlinNullPointerException, IllegalStateException, IllegalArgumentException, and TypeCastException. It applies to:

--Operator, method preamble parameter null check --Platform type expression null check --As operator of type other than null

From a developer's point of view, it doesn't change much. The Kotlin code throws an exception with the same error message as before. The types of exceptions change, but the information passed does not. The following code currently throws an IllegalStateException with the error message "avaCode.getNull () must not be null".

fun main() {
    duplicate(JavaCode.getNull())  // 1
}

fun duplicate(s: String) = s + s
public class JavaCode {
    public static String getNull() { return null; }
}

A special check works that throws an exception when JavaCode.getNull () stores null. Starting with Kotlin 1.4, this code throws a NullPointerException instead of the error message "JavaCode.getNull () must not be null".

This change can reduce null check iterations and reduce the number of null checks present in bytecode.

Standard Library changes

: information_source: All newly added functions are "experimental" functions

Duration and time measurement API A preview version of the new duration and time measurement API is available. Duration can be measured in various units such as seconds, milliseconds, and nanoseconds. Different units are confusing and cause bugs. If the API expects a period of time to be stored as a Long-like primitive value, the unit, type system will not help prevent that. Creating a regular class and saving the time period solves this problem, but it causes extra allocation problems.

Inline classes provide a sophisticated solution to the above problems. It provides both a type system guarantee and an unassigned approach. The API will now be able to use the Duration type, which requires all clients to explicitly specify the time in the desired unit. Duration is declared as an inline class, so there are no extra allocations internally.

import kotlinx.coroutines.delay
import kotlin.time.*

@ExperimentalTime
suspend fun greetAfterTimeout(duration: Duration) {
    delay(duration.toLongMilliseconds())
    println("Hi!")
}

@UseExperimental(ExperimentalTime::class)
suspend fun main() {
    greetAfterTimeout(100.milliseconds)
    greetAfterTimeout(1.seconds)
}

This release supports Mono Clock, which represents a monotonous clock. The recommended approach for measuring duration from a particular point in the program is to use a system time-independent monotonic clock. System time is subject to change externally, which can lead to incorrect behavior. A monotonous clock can only measure the time difference between specified points in time, but it does not know the "current time".

The Clock interface provides a common API for measuring time intervals. MonoClock is an object that implements Clock. Provides a default source for monotonous time on different platforms.

When using the Clock interface, explicitly mark the start time of the action and later mark the elapsed time from the start point. This is especially useful for starting and ending time measurements from a variety of features.

import kotlin.time.*

@UseExperimental(ExperimentalTime::class)
fun main() {
    val clock = MonoClock
    val mark = clock.markNow() // might be inside the first function
    Thread.sleep(10)           // action
    println(mark.elapsedNow()) // might be inside the second function
}

You can use the measureTimedValue function to measure the duration of a particular action and get the result along with the duration of the elapsed time interval. Measure the elapsed time with MonoClock.

import kotlin.time.*

@UseExperimental(ExperimentalTime::class)
fun main() {
    val (value, duration) = measureTimedValue {
        Thread.sleep(100)
        42
    }
    println(value)     // 42
    println(duration)  // e.g. 103 ms
}

For more information on implementing the Duration class, as well as the Clock interface and MonoClock implementation on different platforms, see KEEP. Please see .md). Please note that this API is experimental and subject to change based on feedback.

Bit manipulation function

An API for bit manipulation has been experimentally implemented in the Standard Library.

@UseExperimental(ExperimentalStdlibApi::class)
fun main() {
    val number = "1010000".toInt(radix = 2)
    println(number.countOneBits())
    println(number.countTrailingZeroBits())
    println(number.takeHighestOneBit().toString(2))
    println(number.rotateRight(3).toString(2))
    println(number.rotateLeft(3).toString(2))
}

IntelliJ IDEA support

Java-to-Kotlin converter improvements

We plan to improve the Java to Kotlin converter to minimize the amount of code that is manually modified after conversion. Most current converters generate non-nullable types, so nullability issues will need to be fixed manually later. In many cases, a runtime error can occur later due to a nullability mismatch.

A new and improved version of the Java-to-Kotlin converter attempts to more accurately guess nullability based on the use of Java types in your code. There is no goal of writing 100% error-free code. The goal is to reduce the number of compilation errors and make the generated Kotlin code easier to work with. The new converter also fixes many other known bugs. For example, it now handles implicit Java typecasts correctly.

In the future, the new converter will be the default converter. Available in preview in this release. To turn it on, specify the "Use New J2K (experimental)" flag in the settings.

Debugging improvements

Improved the way the Kotlin “Variables” view selects the variables to display. Due to the large amount of additional technical information in bytecode, only relevant variables are highlighted in the “Variables” view. Setting breakpoints inside lambdas (inline or non-inline) now works better. The parameters of local variables in the lambda and variables and external functions captured from the external context are displayed correctly.

image.png

If desired, you can set a breakpoint at the end of the function.

image.png

evaluate_expression2.gif

Support for the "Evaluate Expressions" feature has been improved in many important language features, such as local extensions and accessors for member extension properties. In addition, you can now change variables with the "Evaluate Expression" function.

New intent and inspection

New intents and tests have been added. One of the goals is to help you learn how to write idiomatic Kotlin code. For example, we suggest using the indexes property instead of manually constructing the index range. indices-gif.gif

If you don't use an index, the loop can be automatically replaced with an element for loop.

--You can automatically replace the lateinit property of a primitive type with the by Delegates.notNull () syntax. --You can convert regular properties to lazy properties and vice versa. --It suggests detecting the use of Java methods for array comparisons (such as Arrays.equals () and Array.deepEquals ()) and replacing them with their corresponding Kotlin (such as contentEquals and contentDeepEquals). --Highlight deprecated imports.

Kotlin/JS --Added support for building and running Kotlin / JS Gradle projects using the org.jetbrains.kotlin.js plugin on Windows. --Like other platforms, you can use Gradle tasks to build and run projects, resolving NPM dependencies required for Gradle configuration. --You can now run your application using webpack-dev-server. No need to manually install and manage node, npm, or Yarn distributions like any other platform. --Up to 30% faster Kotlin / JS performance compared to Kotlin 1.3.41. --Improved integration with NPM allows projects to be delayed and resolved in parallel, adding support for projects with transitive dependencies between compilations of the same project. --Changed the structure and naming of the generated artifacts. --The generated artifacts will now be bundled in the distribution folder, including the project version number and archiveBaseName (default is the project name). projectName-1.0-SNAPSHOT.js.

Dukat You can automatically convert TypeScript declaration files (.d.ts) to Kotlin external declarations (replaces the ts2kt command line tool). Kotlin makes it comfortable to use the libraries of the JavaScript ecosystem in a type-safe way, as it greatly reduces the need to manually write wrappers for JS libraries.

Kotlin / JS will experimentally support dukat integration for Gradle projects. By running a build task in Gradle, a type-safe wrapper is automatically generated for your npm dependencies and you can use it from Kotlin. kotlin-dukat-video.gif

Kotlin/Native --Kotlin / Native version unified with Kotlin --Pre-imported Apple framework introduced for all platforms including macOS and iOS --The Kotlin / Native compiler includes the actual bitcode in the generated framework --Supports kotlin.Deprecated annotation when creating framework --The getOriginalKotlinClass () function has been added to the standard library to allow you to get a KClass from an Objective-C class or protocol. --Standard library supports Kotlin / Native type kotlin.reflect.typeOf () function --executeAfter () added to Worker type. Delay the action. In addition, workers can now call the processQueue () function to explicitly process task queues. --ByteArray.stringFromUtf8 () and ByteArray.stringFromUtf8OrThrow () have been deprecated --Implementation of ByteArray.toKString () function --kotlin-platform-native Gradle plugin is abolished and kotlin-multiplatform Gradle plugin is adopted.

Multi-platform project

Java compilation can now be included in Kotlin / JVM targets for multi-platform projects by calling the newly added withJava () function in the DSL. Configure the Java plugin to use the src / Main / java and src / Test / java paths by default.

plugins { 
    kotlin("multiplatform") version "1.3.50"
}
kotlin {
    jvm {
        withJava()
    }
}

Kotlin's New Project Wizard now generates a Gradle Kotlin DSL for new projects.

Debugging Kotlin / Native code in IntelliJ IDEA Ultimate is now also supported. Native Debug for IntelliJ IDEA Ultimate

image.png

Scripting Multiple features have been added to improve scripting and REPL support. A library that implements the default JSR-223 just by adding kotlin-scripting-jsr223 as a dependency and using javax It will be available.

Properties set via the JSR-223 API can now be accessed from scripts as regular Kotlin properties (previously you had to use binding maps).

Reference: Try Java's JSR-223 implementation

val engine = ScriptEngineManager().getEngineByExtension("kts")!!
engine.put("z", 42)
engine.eval("""println("answer = $z")""")

In addition to annotations such as Repository and DependsOn for resolving dependencies, we now support @Import annotations that tell the script compiler to "import" another script into the current script.

// common.main.kts:
val foo = "common foo"
// script.main.kts:
@file:Import("common.main.kts")
val bar = "bar with $foo"

At the end

Kotlin 1.4 is about to be seen. Kotlin / JS and Kotlin / Native are also being actively improved, and I'm looking forward to seeing how Kotlin will grow in the future. I will continue to watch: sunglasses:

This article is also compatible with Kotlin 1.3.50! Asynchronous processing of HTTP communication with coroutines (Async, Await) of Android + Kotlin 1.3

Recommended Posts

Kotlin 1.3.50 has been released !!
Macchinetta has been released
Resilience4j document Japanese translation (unofficial) has been released
Java SE 13 (JSR388) has been released so I tried it
Introductory hands-on for beginners of Spring 5 & Spring Boot 2 has been released
Kotlin has no ternary operator (conditional operator)
The JacocoReportBase.setClassDirectories (FileCollection) method has been deprecated.