Kotlin 和 Java 一樣,可以在PC上運行,可以用IDEA進行開發(fā),環(huán)境配置參考Getting Started with IntelliJ IDEA。
官方提供了一個學(xué)習(xí)網(wǎng)站,可以運行一些例子Kotlin。
也可以通過命令行的方式編譯運行,參考Working with the Command Line Compiler
PC
fun main(args: Array<String>) {
println("Hello, World!")
}
如上,是一個最簡單的 Hello World。
Android
package com.hello.test
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
textView.text = "Hello World!" // same ass textView.setText()
}
}
入門
Kotlin代碼文件以.kt后綴,源代碼所在的目錄結(jié)構(gòu)不必與包結(jié)構(gòu)保持一致,但最好和Java一樣,目錄和包名一致。
- Kotlin兼容Java,可以直接調(diào)用Java代碼;
- 與Java相比,行結(jié)束不需要分號;
- 包定義和import語句跟Java一樣;
- 變量的定義,” 變量: 類型 “ 的形式,如 savedInstanceState: Bundle?(?表示變量可為null);
- 函數(shù)定義以 fun 開頭, 如 fun test(arg: String): Int;
- 類定義以 class開頭,如 class MainActivity : AppCompatActivity()。
參考*
Getting Started with IntelliJ IDEA
Working with the Command Line Compiler