《Kotlin 程序設計》第二章 快速開始:HelloWorld

第二章 快速開始:HelloWorld

使用云端在線IDE學習Kotlin

我們不需要搭建任何環境,只要有一臺能聯網的設備,打開瀏覽器訪問:

https://try.kotlinlang.org

你就可以盡情享受Kotlin的樂趣了。

使用本地命令行環境編譯執行Kotlin代碼

當然,我們也可以搭建本地環境,編譯執行kotlin代碼。

程序的本質就是映射(函數)。比如說kotlinc這個程序,我們知道,Kotlin基于Java虛擬機(JVM),通過Kotlinc編譯器生成的JVM字節碼與Java編譯的字節碼基本相同,也因此與Java可以完全兼容,并且語法更加簡潔。

Downloading the compiler

Every release ships with a standalone version of the compiler. We can download it from [GitHub Releases]({{ site.data.releases.latest.url }}). The latest release is {{ site.data.releases.latest.version }}.

Manual Install

Unzip the standalone compiler into a directory and optionally add the bin directory to the system path. The bin directory contains the scripts needed to compile and run Kotlin on Windows, OS X and Linux.

SDKMAN!

An easier way to install Kotlin on UNIX based systems such as OS X, Linux, Cygwin, FreeBSD and Solaris is by using SDKMAN!.
Simply run the following in a terminal and follow any instructions:

   $ curl -s https://get.sdkman.io | bash

Next open a new terminal and install Kotlin with:

   $ sdk install kotlin

Homebrew

Alternatively, on OS X you can install the compiler via Homebrew.

   $ brew update
   $ brew install kotlin

MacPorts

If you're a MacPorts user, you can install the compiler with:

   $ sudo port install kotlin

Creating and running a first application

  1. Create a simple application in Kotlin that displays Hello, World!. Using our favorite editor, we create a new file called hello.kt with the following:

    fun main(args: Array<String>) {
        println("Hello, World!")
    }
    
  2. Compile the application using the Kotlin compiler

    $ kotlinc hello.kt -include-runtime -d hello.jar
    

    The -d option indicates what we want the output of the compiler to be called and may be either a directory name for class files or a .jar file name. The -include-runtime option makes the resulting .jar file self-contained and runnable by including the Kotlin runtime library in it.
    If you want to see all available options run

    $ kotlinc -help
    
  3. Run the application.

    $ java -jar hello.jar
    

Compiling a library

If you're developing a library to be used by other Kotlin applications, you can produce the .jar file without including the Kotlin runtime into it.

   $ kotlinc hello.kt -d hello.jar

Since binaries compiled this way depend on the Kotlin runtime you should make sure the latter is present in the classpath whenever your compiled library is used.

You can also use the kotlin script to run binaries produced by the Kotlin compiler:

   $ kotlin -classpath hello.jar HelloKt

HelloKt is the main class name that the Kotlin compiler generates for the file named hello.kt.

Running the REPL

We can run the compiler without parameters to have an interactive shell. We can type any valid Kotlin code and see the results.

[圖片上傳失敗...(image-82eb40-1541525953222)]}})

Using the command line to run scripts

Kotlin can also be used as a scripting language. A script is a Kotlin source file (.kts) with top level executable code.

   import java.io.File

   val folders = File(args[0]).listFiles { file -> file.isDirectory() }
   folders?.forEach { folder -> println(folder) }

To run a script, we just pass the -script option to the compiler with the corresponding script file.

   $ kotlinc -script list_folders.kts <path_to_folder_to_inspect>

使用 Intelli IDEA開發Kotlin程序

Kotlin是JVM上的語言,運行環境需要JDK環境。如果我們學習Kotlin,就不建議使用eclipse了。畢竟Kotlin是JetBrains家族的親兒子,跟Intelli IDEA是血濃于水啊。

我們使用IDEA新建gradle項目,選擇Java,Kotlin(Java)框架支持,如下圖:

新建完項目,我們寫一個HelloWorld.kt類

package com.easy.kotlin

/**
 * Created by jack on 2017/5/29.
 */

import java.util.Date
import java.text.SimpleDateFormat

fun main(args: Array<String>) {
    println("Hello, world!")
    println(SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date()))
}

整體的項目目錄結構如下

.
├── README.md
├── build
│   ├── classes
│   │   └── main
│   │       ├── META-INF
│   │       │   └── easykotlin_main.kotlin_module
│   │       └── com
│   │           └── easy
│   │               └── kotlin
│   │                   └── HelloWorldKt.class
│   └── kotlin-build
│       └── caches
│           └── version.txt
├── build.gradle
├── settings.gradle
└── src
    ├── main
    │   ├── java
    │   ├── kotlin
    │   │   └── com
    │   │       └── easy
    │   │           └── kotlin
    │   │               └── HelloWorld.kt
    │   └── resources
    └── test
        ├── java
        ├── kotlin
        └── resources

21 directories, 7 files

直接運行HelloWorld.kt,輸出結果如下

Hello, world!
2017-05-29 01:15:30

關于工程的編譯、構建、運行,是由gradle協同kotlin-gradle-plugin,在kotlin-stdlib-jre8,kotlin-stdlib核心依賴下完成的。build.gradle配置文件如下:

group 'com.easy.kotlin'
version '1.0-SNAPSHOT'

buildscript {
    ext.kotlin_version = '1.1.1'

    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

apply plugin: 'java'
apply plugin: 'kotlin'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

工程源碼地址:https://github.com/EasyKotlin/easykotlin/tree/easykotlin_hello_world_20170529

使用Android Studio開發 Kotlin Android應用

2017谷歌I/O大會:宣布 Kotlin 成 Android 開發一級語言。

2017谷歌I/O大會上,谷歌宣布,將Kotlin語言作為安卓開發的一級編程語言。Kotlin由JetBrains公司開發,與Java100%互通,并具備諸多Java尚不支持的新特性。谷歌稱還將與JetBrains公司合作,為Kotlin設立一個非盈利基金會。

JetBrains在2010年首次推出Kotlin編程語言,并在次年將之開源。下一版的AndroidStudio(3.0)也將提供支持。

下面我們簡要介紹如何在Android上開始一個Kotlin的HelloWorld程序。

對于我們程序員來說,我們正處于一個美好的時代。得益于互聯網的發展、工具的進步,我們現在學習一門新技術的成本和難度都比過去低了很多。

假設你之前沒有使用過Kotlin,那么從頭開始寫一個HelloWorld的app也只需要這么幾步:

1.首先,你要有一個Android Studio。

本書中,筆者用的是2.2.3版本,其它版本應該也大同小異。

Android Studio 2.3.1
Build #AI-162.3871768, built on April 1, 2017
JRE: 1.8.0_112-release-b06 x86_64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o

2.其次,安裝一個Kotlin的插件。

依次打開:Android Studio > Preferences > Plugins,

然后選擇『Browse repositories』,在搜索框中搜索Kotlin,結果列表中的『Kotlin』插件,如下圖

點擊安裝,安裝完成之后,重啟Android Studio。

3.新建一個Android項目

重新打開Android Studio,新建一個Android項目吧,添加一個默認的MainActivity——像以前一樣即可。

4.Java to Kotlin

安裝完插件的AndroidStudio現在已經擁有開發Kotlin的功能。我們先來嘗試它的轉換功能:Java -> Kotlin,可以把現有的java文件翻譯成Kotlin文件。

打開MainActivity文件,在Code菜單下面可以看到一個新的功能:Convert Java File to Kotlin File。

點擊轉換,

可以看到轉換后的Kotlin文件:MainActivity.kt

package com.kotlin.easy.kotlinandroid

import android.support.v7.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

這個轉換功能,對我們Java程序員在學習Kotlin是十分實用。我們可以基于我們之前的Java編碼的經驗來迅速學習Kotlin編程。

5.配置gradle文件

MainActivity已經被轉換成了Kotlin實現,但是項目目前gradle編譯、構建、運行還不能執行,還需要進一步配置一下,讓項目支持grade的編譯、運行。當然,這一步也不需要我們做太多工作——IDEA都已經幫我們做好了。

在Java代碼轉換成Kotlin代碼之后,打開MainActivity.kt文件,編譯器會提示"Kotlin not configured",點擊一下Configure按鈕,IDEA就會自動幫我們把配置文件寫好了。

我們可以看出,主要的依賴項是:

kotlin-gradle-plugin
plugin: 'kotlin-android'
kotlin-stdlib-jre7

完整的配置文件如下:

Project build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

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"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Module build.gradle

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()
}

所以說使用IDEA來寫Kotlin代碼,這工具的完美集成會讓你用起來如絲般潤滑。畢竟Kotlin的親爸爸JetBrains是專門做工具的,而且Intelli IDEA又是那么敏捷、智能。

配置之后,等Gradle Sync完成,即可運行。

6.運行

運行結果如下

工程源碼:https://github.com/EasyKotlin/KotlinAndroid

參考資料

1.https://www.kotliner.cn/2017/03/13/%E5%BF%AB%E9%80%9F%E4%B8%8A%E6%89%8B%20Kotlin%2011%E6%8B%9B/


Kotlin開發者社區

專注分享 Java、 Kotlin、Spring/Spring Boot、MySQL、redis、neo4j、NoSQL、Android、JavaScript、React、Node、函數式編程、編程思想、"高可用,高性能,高實時"大型分布式系統架構設計主題。

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

分布式框架:Zookeeper、分布式中間件框架等
分布式存儲:GridFS、FastDFS、TFS、MemCache、redis等
分布式數據庫:Cobar、tddl、Amoeba、Mycat
云計算、大數據、AI算法
虛擬化、云原生技術
分布式計算框架:MapReduce、Hadoop、Storm、Flink等
分布式通信機制:Dubbo、RPC調用、共享遠程數據、消息隊列等
消息隊列MQ:Kafka、MetaQ,RocketMQ
怎樣打造高可用系統:基于硬件、軟件中間件、系統架構等一些典型方案的實現:HAProxy、基于Corosync+Pacemaker的高可用集群套件中間件系統
Mycat架構分布式演進
大數據Join背后的難題:數據、網絡、內存和計算能力的矛盾和調和
Java分布式系統中的高性能難題:AIO,NIO,Netty還是自己開發框架?
高性能事件派發機制:線程池模型、Disruptor模型等等。。。

合抱之木,生于毫末;九層之臺,起于壘土;千里之行,始于足下。不積跬步,無以至千里;不積小流,無以成江河。

Kotlin 簡介

Kotlin是一門非研究性的語言,它是一門非常務實的工業級編程語言,它的使命就是幫助程序員們解決實際工程實踐中的問題。使用Kotlin 讓 Java程序員們的生活變得更好,Java中的那些空指針錯誤,浪費時間的冗長的樣板代碼,啰嗦的語法限制等等,在Kotlin中統統消失。Kotlin 簡單務實,語法簡潔而強大,安全且表達力強,極富生產力。

Java誕生于1995年,至今已有23年歷史。當前最新版本是 Java 9。在 JVM 生態不斷發展繁榮的過程中,也誕生了Scala、Groovy、Clojure 等兄弟語言。

Kotlin 也正是 JVM 家族中的優秀一員。Kotlin是一種現代語言(版本1.0于2016年2月發布)。它最初的目的是像Scala那樣,優化Java語言的缺陷,提供更加簡單實用的編程語言特性,并且解決了性能上的問題,比如編譯時間。 JetBrains在這些方面做得非常出色。

Kotlin語言的特性

用 Java 開發多年以后,能夠嘗試一些新的東西真是太棒了。如果您是 Java 開發人員,使用 Kotlin 將會非常自然流暢。如果你是一個Swift開發者,你將會感到似曾相識,比如可空性(Nullability)。 Kotlin語言的特性有:

1.簡潔

大幅減少樣板代碼量。

2.與Java的100%互操作性

Kotlin可以直接與Java類交互,反之亦然。這個特性使得我們可以直接重用我們的代碼庫,并將其遷移到 Kotlin中。由于Java的互操作性幾乎無處不在。我們可以直接訪問平臺API以及現有的代碼庫,同時仍然享受和使用 Kotlin 的所有強大的現代語言功能。

3.擴展函數

Kotlin 類似于 C# 和 Gosu, 它提供了為現有類提供新功能擴展的能力,而不必從該類繼承或使用任何類型的設計模式 (如裝飾器模式)。

4.函數式編程

Kotlin 語言一等支持函數式編程,就像Scala一樣。具備高階函數、Lambda 表達式等函數式基本特性。

5.默認和命名參數

在Kotlin中,您可以為函數中的參數設置一個默認值,并給每個參數一個名稱。這有助于編寫易讀的代碼。

6.強大的開發工具支持

而由于是JetBrains出品,我們擁有很棒的IDE支持。雖然Java到Kotlin的自動轉換并不是100% OK 的,但它確實是一個非常好的工具。使用 IDEA 的工具轉換Java代碼為 Kotlin 代碼時,可以輕松地重用60%-70%的結果代碼,而且修改成本很小。

Kotlin 除了簡潔強大的語法特性外,還有實用性非常強的API以及圍繞它構建的生態系統。例如:集合類 API、IO 擴展類、反射API 等。同時 Kotlin 社區也提供了豐富的文檔和大量的學習資料,還有在線REPL。

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

圖來自《Kotlin從入門到進階實戰》 (陳光劍,清華大學出版社)
圖來自《Kotlin從入門到進階實戰》 (陳光劍,清華大學出版社)

https://kotlinlang.org/

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,619評論 6 539
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,155評論 3 425
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 177,635評論 0 382
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,539評論 1 316
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,255評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,646評論 1 326
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,655評論 3 444
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,838評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,399評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,146評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,338評論 1 372
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,893評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,565評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,983評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,257評論 1 292
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,059評論 3 397
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,296評論 2 376

推薦閱讀更多精彩內容