- Print the Log
Log.d(TAG , "print i = $i , j = $j , len = ${str.length} ")Copy the code
- Set the listeners
myButton.setOnClickListener { navigateToDetail() }Copy the code
- Scope in the for statement
In Java:for (int i = 1; i< =10 ; i++) { } for (int i = 1; i < 10 ; i++) { } for (int i = 10; i> =0 ; i-) {}for (int i = 1; i< =10 ; i+ =2) {}for (int i = 10; i> =0 ; i- =2) {}for (String item : collection) { } for (Map.Entry<String, String> entry: map.entrySet()) { }Copy the code
In Kotlin:
for (i in 1.10) {}for (i in 1 until 10) {}for (i in 10 downTo 0) {}for (i in 1.10 step 2) {}for (i in 10 downTo 1 step 2) {}for (item in collection) { } for ((key, value) in map) { }Copy the code
- A function with an indeterminate number of arguments
In Java we can define a function with an unlimited number of arguments:void doSomething(int. numbers) {}Copy the code
In Kotlin we use the vararg keyword, which is used the same way:
fun doSomething(vararg numbers: Int) {}Copy the code
- Handler and Thread can be written more succinctly
view.postDelayed({ doWhatever() }, 200) Thread().run { // Running in a thread }Copy the code
- Eliminate unnecessary code
In Java, we often have to determine if a class object is empty, whereas in Kotlin, objects are usually non-empty, unless you define? Number, so that you don’t have to always add null judgments in your code.val str : String = null / / an error val str : String? = null / / normalCopy the code
And Kotlin’s judgment of space is also succinct:
val nullStr : String? = nullval size : Int = nullStr? .length ? :0 // Return 0 if nullStr is nullCopy the code
- Parsing the layout
We used to use Java to inflate a layout like this:LayoutInflater.from(parent.getContext()).inflate(R.id.my_layout, parent, false);Copy the code
In Kotlin, we can define extension functions:
fun ViewGroup.inflate(@LayoutRes layoutRes: Int, attachToRoot: Boolean = false): View { return LayoutInflater.from(context).inflate(layoutRes, this, attachToRoot) }Copy the code
So in code we can use it like this:
parent.inflate(R.layout.my_layout) parent.inflate(R.layout.my_layout, true)Copy the code
- ImageView loads web images
We still define an extension function for ImageView, using your image-loading library, such as Picasso:fun ImageView.loadUrl(url: String) { Picasso.with(context).load(url).into(this)}Copy the code
So in code we can use it like this:
imageView.loadUrl("http://.... /")Copy the code
- Processing the Options Menu
In Java, we typically use switch for multiple choices, whereas in Kotlin, we can use when:override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { R.id.action_settings -> consume { navigateToSettings() } R.id.nav_camera -> drawer.consume { navigateToCamera() } R.id.nav_gallery -> drawer.consume { loadGallery() } R.id.nav_slideshow -> drawer.consume { loadSlideshow() } else -> super.onOptionsItemSelected(item) }Copy the code
The consume function is an inline function:
inline fun consume(f: () -> Unit): Boolean { f() return true }Copy the code
- Initialize the controller
In Java, we normally call findViewByID after setContentView to initialize the controller, whereas Kotlin uses lazy loading:override val textView by lazy { findViewById(R.id.sample_text) as TextView } override val dataBase by lazy { DataBase(this)}override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail) textView.setText(R.string.text) dataBase.loadWhatever() }Copy the code
- Processing collection class
The collection class in Kotlin provides a number of handlers to call, such as filter, sort, and Map.returnparsedContacts.filter { it.name ! =null&& it.image ! =null} .sortedBy { it.name } .map { Contact(it.id, it.name!! , it.image!!) ] }Copy the code
- Defining data classes
When Java defines data classes, getters, setters, toString(), equals()… We have to write it ourselves, so we don’t have to do that in Kotlin.data class Person(val name: String, val surname: String, val age: Int)Copy the code
- Define constants
object DefaultValues { val FILES_TO_DOWNLOAD = 100 } class DefaultValues private constructor(a){ companion object { val FILES_TO_DOWNLOAD = 100}}// Only at top level const val DEFAULT_FILES_TO_DOWNLOAD = 100Copy the code
- Define the singleton
class Singleton private constructor(a){ private object Holder { val INSTANCE = Singleton() } companion object { val instance: Singleton by lazy { Holder.INSTANCE } } }Copy the code
reference
Kotlin awesome tricks for Android
kotlin vs java