白季飞龙的个人主页

Kotlin大杂烩

1. 编写Hello World

App.kt

fun main(args: Array<String>) {
    println("HelloKT")
}

2. 编译与运行Hello World

  1. kotlinc App.kt 在当前目录编译生成AppKt.class
  2. kotlin AppKt 运行类AppKt(等价于java AppKt带上Kotlin的依赖库)

3. 在Gradle中使用

Gradle配置Kotlin,需要一个插件(Kotlin的Gradle插件kotlin-gradle-plugin) 和一个依赖(Kotlin标准库kotlin-stdlib)

build.gradle

buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.50'
    }
}

apply plugin: 'application'
apply plugin: 'kotlin'

mainClassName = 'MyApp'

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

repositories {
    jcenter()
}

添加"kotlin"插件后,就不需要"java"插件了

MyApp.kt

/**
 * Created by BaiJiFeiLong@gmail.com at 18-6-27 下午10:08
 */
class MyApp {
    companion object {
        @JvmStatic
        fun main(args: Array<String>) {
            println("hello kt")
        }
    }
}

Kotlin文件可以放在src/main/java中,也可以放在src/main/kotlin中,默认情况下都能识别

之所以把main方法写到类里面,是因为Gradle的Application插件(gradle run)需要运行 指定类(mainClassName)的main方法,所以main方法必须放在类中,否则Application插件无法工作

运行程序:gradle run

4. 用Gradle构建Kotlin版的SpringBoot应用

build.gradle

buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.50'
        classpath 'org.springframework.boot:spring-boot-gradle-plugin:2.0.3.RELEASE'
    }
}

apply plugin: 'application'
apply plugin: 'kotlin'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

mainClassName = 'bj.App'

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib"
    compile "org.jetbrains.kotlin:kotlin-reflect" // @Bean @Component needed
    compile 'org.springframework.boot:spring-boot-starter'
}

repositories {
    jcenter()
}

App.kt

package bj

import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.context.event.ApplicationReadyEvent
import org.springframework.context.ApplicationListener

/**
 * Created by BaiJiFeiLong@gmail.com at 18-6-27 下午10:08
 */
@SpringBootApplication
open class App : ApplicationListener<ApplicationReadyEvent> {
    override fun onApplicationEvent(event: ApplicationReadyEvent?) {
        println("Ready.")
    }

    companion object {
        @JvmStatic
        fun main(args: Array<String>) {
            SpringApplication.run(App::class.java, *args);
        }
    }
}

注意:


漫漫路,莫论逍遥;潜心修,只为悟道