Java代码:
if(a != null && a.b != null && a.b.c != null) {
String user = a.b.c.d;
}
Kotlin代码:
val user = a?.b?.c?.d
Java代码:
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Kotlin代码:
class User {
var name : String? = null
}
属性访问对比:
Java代码:
user.setName("Java");
String name = user.getName();
Kotlin代码:
user.name = "Kotlin"
String name = user.name
Java代码:
RequestBean requestBean = new RequestBean();
requestBean.method = AppService.METHOD_CASHIER;
requestBean.cartId = mCartId;
requestBean.merchantOrderInfo = "1234567890";
requestBean.merchantOrderId = "1234567890";
Kotlin代码:
val requestBean = RequestBean().apply {
method = AppService.METHOD_CASHIER
cartId = mCartId
merchantOrderInfo = "1234567890"
merchantOrderId = "1234567890"
}
Java示例:
public class SingletonDemo {
private static SingletonDemo instance = new SingletonDemo();
private SingletonDemo() { }
public static SingletonDemo getInstance() {
return instance;
}
public String getTAG() {
return "Java";
}
}
Kotlin示例:
object SingletonDemo {
fun getTAG(): String {
return "Kotlin"
}
}
project build.gradle添加支持:
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
module build.gradle添加支持:
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
Kotlin调用Java的get/set方法
Java示例:
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return 10;
}
}
Kotlin示例:
val user = User()
user.name = "Kotlin"
println(user.name)
println(user.age)
Kotlin调用Java的静态成员:
Java示例:
public class JDPayDeviceUtil {
public static String getVersionName(Context context, String packageName) {
PackageInfo info = getPackageInfo(context, packageName);
if(info != null) {
return info.versionName;
}
return "";
}
}
Kotlin示例:
val versionName = JDPayDeviceUtil.getVersionName()
println("$versionName")
Kotlin示例:
class KotlinStatic {
companion object {
var number = 0
fun staticMethod(string: String?) {
println(string)
}
}
}
Java示例:
KotlinStatic.Companion.staticMethod("Java");
可以平滑对接网络框架Retrofit、OkHttp、异步框架RxJava、CameraX等。很多主流框架和Google官方Demo也均使用纯Kotlin实现,如:OkHttp、CameraX。
val mediaType = MediaType.parse("text/x-markdown; charset=urg-8")
val requst = Request.Builder()
.url("http://...")
.post(RequestBody.create(mediaType, "kotlin-okhttp"))
.build()
val client = OkHttpClient()
client.newCall(requst).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
TODO("Not yet implemented")
}
override fun onResponse(call: Call, response: Response) {
TODO("Not yet implemented")
}
})
继承Thread类:
object : Thread() {
override fun run() {
println("running thread: ${currentThread()}")
}
}.start()
Kotlin封装类:
thread(start = true) {
println("running thread: ${Thread.currentThread()}")
}
同步线程锁:
@Synchronized fun syncMethod() {
println("kotlin synchronized")
}
fun syncMethod() {
println("kotlin none synchronized")
synchronized(this) {
println("kotlin synchronized")
}
}
Kotlin协程/ Coroutines:
阻塞协程:
Log.d("Kotlin","thread id: ${mainLooper.thread.id}")
runBlocking {
repeat(8) {
Log.d("Kotlin","current thread: ${Thread.currentThread().id}")
delay(1000)
}
}
Log.d("Kotlin", "Blocking Coroutines END")
异步协程:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val job = GlobalScope.launch {
delay(2000)
Log.d("Kotlin", "Coroutines thread id:${Thread.currentThread().id}")
}
Log.d("kotlin", "main thread END")
}
Java示例:
public static void writeText(String fileName, String txt) {
try {
FileOutputStream outputStream = new FileOutputStream(fileName);
outputStream.write(txt.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Kotlin示例:
File(fileName).writeText(txt)
File(fileName).appendText(txt)
File(fileName).writeBytes(arrayBytes)
File(fileName).appendBytes(arrayBytes)
val content = File(fileName).readText()
val bytes = File(fileName).readBytes()
val line = File(fileName).readLines()
val bitmap = BitmapFactory.decodeFile(fileName)
Kotlin同样支持SQLite、Room数据库,与Java用法基本一致。
针对SQLite访问数据库,这里引用官方教程的一段话:
如果你使用了SQLiteOpenHelper,你可以调用getReadableDatabase()或者getWritableDatabase()(在生产环境的代码中产生的结果是一样的),但是之后你必须在接收到SQLiteDatabase的中调用close() 方法。你也必须在某个地方缓存助手类,同时,如果你从多个线程中使用了它,还得注意并发访问的问题。
有鉴于此,Kotlin结合Anko库推出了改良版的SQLite管理工具:ManagedSQLiteOpenHelper。
Kotlin加载网页:
webView.loadUrl("https://www.jd.com/")
物理返回键返回事件:
override fun onBackPressed() {
if(webView.canGoBack()) {
webView.goBack()
return
}
super.onBackPressed()
}
Js与Kotlin互操作:
private fun initView() {
val webSettings = webView.settings
webSettings.javaScriptEnabled = true
webView.addJavascriptInterface(JsToKotlin(), "Android")
webView.loadUrl("https://www.jd.com/web/KotlinToJs.html")
}
private fun KotlinCallJs(string: String) {
webView?.loadUrl("javascript:kotlinCallJs('$string')")
}
internal inner class JsToKotlin {
@JavascriptInterface
fun show() {
println("kotlin被js调用了")
}
}
标识JNI方法关键字区别:
Java:native
Kotlin:external
Java示例:
public class SerialPort {
static {
System.loadLibrary("nativeJD");
}
public native String stringFromJNI();
}
Kotlin示例:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val string = stringFromJNI()
}
external fun stringFromJNI(): String
companion object {
init {
System.loadLibrary("nativeJD")
}
}
}