"Kotin Minimalist Tutorial" Chapter 12 Use Kotlin to integrate Gradle development

Chapter 12 Using Kotlin to Integrate Gradle Development

Because Kotlin has a wealth of features, such as first-class functions and extension methods, it can retain and improve the best parts of Gradle build scripts-including concise declarative syntax and the ability to easily make DSLs.

The Gradle team worked closely with the Kotlin team to develop a new Kotlin script-based build configuration language for Gradle. We call it Gradle Script Kotlin, which supports the use of Kotlin to write build and configuration files. At the same time, it also supports functions such as automatic completion and compilation checking in the IDE. With Gradle Script Kotlin, we can use Kotlin to write configuration files, just like writing ordinary code.

We have used Gradle in many sample projects in the previous chapters to build our Kotlin projects. In this chapter, we will systematically introduce the related content of using Kotlin to integrate Gradle development.

12.1 Use Gradle to build Kotlin project

12.1.1 kotlin-gradle plugin

In order to build a Kotlin project with Gradle, we need to set up the kotlin-gradle plugin:

buildscript {
	ext {
		kotlinVersion = '1.1.3-2'
	}
	repositories {
		mavenCentral()
	}
	dependencies {
		classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${kotlinVersion}")
                ...
	}
}

apply plugin: 'kotlin'

And add kotlin-stdlib dependency:

dependencies {
	compile("org.jetbrains.kotlin:kotlin-stdlib-jre8:${kotlinVersion}")
	compile("org.jetbrains.kotlin:kotlin-reflect:${kotlinVersion}")
}

Of course, for these operations when we create a new project, usually we only need to select the corresponding options, and IntelliJ IDEA will directly help us complete the basic configuration.

We used kotlin-gradle-pluginto compile Kotlin source code and modules. Kotlin version used is usually defined as kotlinVersionproperty.

For JVM, we need to apply Kotlin plugin:

apply plugin: "kotlin"

12.1.2 Kotlin and Java mixed programming

Kotlin source code can be mixed with Java source code in the same folder or in different folders. The default convention is to use a different folder:

sourceSets {
    
    
    main.kotlin.srcDirs += 'src/main/kotlin'
    main.java.srcDirs += 'src/main/java'
}

If you use the default directory, the above configuration can be omitted.

If you do not use the default convention, you should update the corresponding sourceSets attribute

sourceSets {
    
    
    main.kotlin.srcDirs += 'src/main/myKotlin'
    main.java.srcDirs += 'src/main/myJava'
}

12.1.3 Configure Gradle JavaScript Project

When targeting JavaScript, different plug-ins must be applied:

apply plugin: "kotlin2js"

In addition to the output JavaScript file, the plugin will create an additional JS file with a binary descriptor by default.

If it is to build a reusable library that other Kotlin modules can rely on, then this file is necessary and distributed with the conversion result.

Generated by the binary descriptor file kotlinOptions.metaInfooption controls:

compileKotlin2Js {
    
    
	kotlinOptions.metaInfo = true
}

Tip: For example projects, please refer to
https://github.com/EasyKotlin/chapter2_hello_world_kotlin2js

12.1.4 Configure Gradle Android Project

Android's Gradle model is a bit different from ordinary Gradle, so if we want to build an Android project written in Kotlin, we need to replace the kotlin plugin with the kotlin-android plugin:

buildscript {
    
    
    ext.kotlin_version = '1.1.2-4'
    repositories {
    
    
        jcenter()
    }
    dependencies {
    
    
        classpath 'com.android.tools.build:gradle:2.3.1'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

Usually we use Android Studio to generate a project with app sub-projects. The implementation of multi-project configuration is usually to include all projects as subfolders under a root project path. For example, we configure the following in settings.gradle under the project root path:

include ':app'

Each subproject has its own build.gradle file to declare how to build it.

For example, a complete configuration in the build configuration file build.gradle of the subproject app is as follows:

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.kotlin.easy.kotlinandroid"
        minSdkVersion 14
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
}
repositories {
    mavenCentral()
}

among them,

apply plugin:'kotlin-android' is a Kotlin Android plugin.
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version" is the Kotlin runtime standard library.

In addition, the directory where Android Studio loads the source code by default is src/main/java. If you want to specify the Kotlin code in the src/main/kotlndirectory, you can add the following content under android:

android {
    
    
  ……
  sourceSets {
    
    
    main.java.srcDirs += 'src/main/kotlin'
  }
}

Tip: For the complete Gradle configuration example of Kotlin Android, please refer to https://github.com/EasyKotlin/KotlinAndroid.

12.1.5 Configure Kotlin standard library dependencies

In addition to the above kotlin-gradle-pluginother than dependency, we also need to add a dependency Kotlin standard library:

repositories {
    
    
    mavenCentral()
}

dependencies {
    
    
    compile "org.jetbrains.kotlin:kotlin-stdlib"
}

If for JavaScript, to use compile "org.jetbrains.kotlin:kotlin-stdlib-js"instead.

If it is for JDK 7 or JDK 8, you can use the extended version of the Kotlin standard library, which contains additional extension functions added to the new version of JDK. Use one of the following dependencies instead kotlin-stdlib:

compile "org.jetbrains.kotlin:kotlin-stdlib-jre7"
compile "org.jetbrains.kotlin:kotlin-stdlib-jre8"

If Kotlin reflection is used in the project, add reflection dependency:

compile "org.jetbrains.kotlin:kotlin-reflect"

If the test framework is used in the project, we add the corresponding test library dependency:

testCompile "org.jetbrains.kotlin:kotlin-test"
testCompile "org.jetbrains.kotlin:kotlin-test-junit"

12.1.6 Incremental compilation

Kotlin supports optional incremental compilation in Gradle. Incremental compilation tracks changes to source files between builds, so only files affected by these changes will be compiled. Starting from Kotlin 1.1.1, incremental compilation is enabled by default.

12.1.7 Compiler options

To specify additional compiler options, you can use Kotlin compilation task compileKotlin the kotlinOptionsproperty.

Example of configuring a single task:

compileKotlin {
    
    
    kotlinOptions {
    
    
        suppressWarnings = true
    }
}

12.2 Use Kotlin to write build and configuration files

What might a way to write Gradle build scripts and plugins based on Kotlin look like? How does it help teams-especially large teams-speed up work and write better structured, more maintainable build scripts?

These possibilities are very tempting.

Because Kotlin is a statically typed language with in-depth support in IDEA and Eclipse, it can provide Gradle users with appropriate IDE support from auto-completion to refactoring, and everything in between. And because Kotlin has rich features, such as first-class functions and extension methods, it can retain and improve the best parts of Gradle build scripts-including concise declarative syntax and the ability to easily make DSLs.

The Gradle team carefully examined these possibilities and worked closely with the Kotlin team to develop a new Kotlin-based build language for Gradle-we call it Gradle Script Kotlin.

Let's briefly introduce the use of Kotlin scripts to write Gradle configuration files.

Let's take the chapter11_kotlin_springboot project in the previous chapter as an example.

First, we create a settings.gradle configuration file in the root directory:

rootProject.name = 'chapter11_kotlin_springboot'
rootProject.buildFileName = 'build.gradle.kts'

Specify the gradle build file name as'build.gradle.kts'.
Then, we create a new'build.gradle.kts', the complete content is as follows:

buildscript {
    val kotlinVersion = "1.1.3-2"
    val springBootVersion = "2.0.0.M2"
    extra["kotlinVersion"] = kotlinVersion

    repositories {
        mavenCentral()
        maven { setUrl("https://repo.spring.io/snapshot") }
        maven { setUrl("https://repo.spring.io/milestone") }
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:$springBootVersion")
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion")
        classpath("org.jetbrains.kotlin:kotlin-allopen:$kotlinVersion")
    }
}

apply {
    plugin("kotlin")
    plugin("kotlin-spring")
    plugin("eclipse")
    plugin("org.springframework.boot")
    plugin("io.spring.dependency-management")
}

version = "0.0.1-SNAPSHOT"

configure<JavaPluginConvention> {
    setSourceCompatibility(1.8)
    setTargetCompatibility(1.8)
}


repositories {
    mavenCentral()
    maven { setUrl("https://repo.spring.io/snapshot") }
    maven { setUrl("https://repo.spring.io/milestone") }
}

val kotlinVersion = extra["kotlinVersion"] as String

dependencies {
    compile("org.springframework.boot:spring-boot-starter-actuator")
    compile("org.springframework.boot:spring-boot-starter-data-jpa")
    compile("org.springframework.boot:spring-boot-starter-freemarker")
    compile("org.springframework.boot:spring-boot-starter-web")
    compile("org.jetbrains.kotlin:kotlin-stdlib-jre8:${kotlinVersion}")
    compile("org.jetbrains.kotlin:kotlin-reflect:${kotlinVersion}")
    runtime("org.springframework.boot:spring-boot-devtools")
    runtime("mysql:mysql-connector-java")
    testCompile("org.springframework.boot:spring-boot-starter-test")
}

Tip: According to the above steps, IDEA may not recognize these DSL functions after creating the file build.gradle.kts. At this time, we can restart IDEA (this is a bug and will be fixed later).

The related functions and classes of Gradle DSL are in the lib directory of the Gradle package: lib/gradle-script-kotlin-(version number).jar. We simply use the following table to illustrate:

Function (class) Corresponding gradle-script-kotlin code
buildscript open fun buildscript(@Suppress(“unused_parameter”) block: ScriptHandlerScope.() -> Unit) = Unit
repositories fun ScriptHandler.repositories(configuration: RepositoryHandler.() -> Unit) =repositories.configuration()
buildscript.dependencies DependencyHandlerScope(scriptHandler.dependencies)
configure inline fun Project.configure(noinline configuration: T.() -> Unit)
Project.dependencies DependencyHandlerScope(dependencies).configuration()

In other words, these configuration functions are actually implemented by Gradle's DSL.

In fact, these configuration syntax looks very similar to Groovy. E.g:

Groovy :

    repositories {
        mavenCentral()
        maven { url "https://repo.spring.io/snapshot" }
        maven { url "https://repo.spring.io/milestone" }
    }

Kotlin:

repositories {
    mavenCentral()
    maven { setUrl("https://repo.spring.io/snapshot") }
    maven { setUrl("https://repo.spring.io/milestone") }
}

Another example:
Groovy:

sourceCompatibility = 1.8
targetCompatibility = 1.8

Kotlin:

configure<JavaPluginConvention> {
    setSourceCompatibility(1.8)
    setTargetCompatibility(1.8)
}

Reminder: The source code of the sample project in this section https://github.com/EasyKotlin/chapter11_kotlin_springboot/tree/build.gradle.kts

chapter summary

In this chapter, we briefly introduce some common configuration methods in the development process of using Kotlin to integrate Gradle. Gradle is a very useful build tool. When the configuration file of our Kotlin project is also Kotlin code, our work is much simpler and we only need to focus on Kotlin.

In the next chapter, we will learn about using Kotlin and Anko for Android development.


Kotlin Developer Community

Focus on sharing Java, Kotlin, Spring/Spring Boot, MySQL, redis, neo4j, NoSQL, Android, JavaScript, React, Node, functional programming, programming ideas, "high availability, high performance, high real-time" large-scale distributed system architecture design theme.

High availability, high performance, high real-time large-scale distributed system architecture design

Distributed framework: Zookeeper, distributed middleware framework, etc.
Distributed storage: GridFS, FastDFS, TFS, MemCache, redis, etc.
Distributed database: Cobar, tddl, Amoeba, Mycat
cloud computing, big data, AI algorithm
virtualization, cloud native Technology
Distributed computing framework: MapReduce, Hadoop, Storm, Flink, etc.
Distributed communication mechanism: Dubbo, RPC calls, shared remote data, message queues, etc.
Message queue MQ: Kafka, MetaQ, RocketMQ
how to build a highly available system: based on hardware, software Realization of some typical solutions such as middleware and system architecture: HAProxy, Corosync+Pacemaker-based high-availability cluster suite middleware system
Mycat architecture distributed evolution
The problems behind big data Join: contradictions and reconciliation of data, network, memory and computing capabilities
High-performance problems in Java distributed systems: AIO, NIO, Netty or self-developed frameworks?
High-performance event dispatch mechanism: thread pool model, Disruptor model, etc. . .

The embracing wood is born at the end of the mill; the nine-story platform starts from the basement; the journey of a thousand miles begins with a single step. If you don't accumulate steps, you can't reach a thousand miles; if you don't accumulate small streams, you can't become a river.

Introduction to Kotlin

Kotlin is a non-research language. It is a very pragmatic industrial-grade programming language. Its mission is to help programmers solve problems in actual engineering practice. Using Kotlin makes the lives of Java programmers better. The null pointer errors in Java, the lengthy boilerplate code that wastes time, the verbose syntax restrictions, etc., all disappear in Kotlin. Kotlin is simple and pragmatic, with concise and powerful syntax, safe and expressive, and extremely productive.

Java was born in 1995 and has a history of 23 years. The current latest version is Java 9. In the process of continuous development and prosperity of the JVM ecosystem, brother languages ​​such as Scala, Groovy, and Clojure were also born.

Kotlin is also an excellent member of the JVM family. Kotlin is a modern language (version 1.0 was released in February 2016). Its original purpose is to optimize the defects of the Java language like Scala, provide simpler and more practical programming language features, and solve performance problems, such as compilation time. JetBrains has done a great job in these areas.

Features of Kotlin language

After developing in Java for many years, it's great to be able to try something new. If you are a Java developer, Kotlin will be very natural and smooth. If you are a Swift developer, you will feel familiar, such as Nullability. The features of Kotlin language are:

1. Concise

Significantly reduce the amount of boilerplate code.

2. 100% interoperability with Java

Kotlin can directly interact with Java classes and vice versa. This feature allows us to directly reuse our code base and migrate it to Kotlin. Because Java's interoperability is almost everywhere. We can directly access platform APIs and existing code bases, while still enjoying and using all the powerful modern language features of Kotlin.

3. Extension function

Kotlin is similar to C# and Gosu, it provides the ability to provide new functional extensions for existing classes without having to inherit from the class or use any type of design patterns (such as decorator patterns).

4. Functional programming

The Kotlin language first supports functional programming, just like Scala. It has basic functional features such as high-order functions and lambda expressions.

5. Default and named parameters

In Kotlin, you can set a default value for the parameters in a function and give each parameter a name. This helps to write easy-to-read code.

6. Powerful development tool support

And because it is produced by JetBrains, we have great IDE support. Although the automatic conversion from Java to Kotlin is not 100% OK, it is indeed a very good tool. When using IDEA's tools to convert Java code to Kotlin code, 60%-70% of the resulting code can be reused easily, and the cost of modification is small.

In addition to its concise and powerful syntax features, Kotlin also has a very practical API and an ecosystem built around it. For example: collection API, IO extension, reflection API, etc. At the same time, the Kotlin community also provides a wealth of documents and a lot of learning materials, as well as online REPL.

A modern programming language that makes developers happier. Open source forever

Picture from "Kotlin from entry to advanced combat" (Chen Guangjian, Tsinghua University Press)

Picture from "Kotlin from entry to advanced combat" (Chen Guangjian, Tsinghua University Press)

https://kotlinlang.org/

Guess you like

Origin blog.csdn.net/universsky2015/article/details/108669427