简体   繁体   中英

logd shortcut doesn't work in Intellij with Kotlin

Logging Java in Intellij is easy with shortcuts such as 'logt', 'logd', 'loge'... and so on. But I moved to Kotlin, I noticed that those shortcuts doesn't work anymore. I don't know if it has something to do with my configuration, but if not, how can I fix this?

You should create separate templates to make them work correctly.
Here is the step-by-step guide:

Firstly, Copy and paste AndroidLog templates to Kotlin (Just select them and use CMD+C, CMD+V (or Ctrl+C, Ctrl+V) Secondly, You have to adjust them manually: 1. logd (and others) Select the logd item and press "Edit variables" 在此处输入图片说明

Change expression to: kotlinFunctionName() 在此处输入图片说明

Also, remove ; from the end of the template, as you don't need it in Kotlin.

Now your method name will be shown correctly

  1. logt This one is a bit trickier. Solution 1 TAG = class name.

    • Template text :

    private val TAG = "$className$"

    • Edit variables -> Expression:

    groovyScript("_1.take(Math.min(23, _1.length()));", kotlinClassName())

Solution 2 TAG = file name (can be used inside Companion)

  • Template text :

    private const val TAG = "$className$

or:

companion object {
     private const val TAG = "$className$"
}
  • Edit variables -> Expression:

    groovyScript("_1.take(Math.min(23, _1.length()));", fileNameWithoutExtension())


Edit 19.02.19

Also, it might be useful for someone.
In order to avoid creating the TAG variable, you can use the class name as a variable, for instance:

Log.d("BaseActivity", "onCreate: ") 

Where BaseActivity is the class name.

The template will look now as:

android.util.Log.d("$CLASS_NAME$", "$METHOD_NAME$: $content$")

Where CLASS_NAME variable is:

groovyScript("_1.take(Math.min(23, _1.length()));", fileNameWithoutExtension())

These are provided in IntelliJ as a Live Template configuration for AndroidLog (found in Preferences -> Editor -> Live Templates ), and are applicable specifically to Java code: AndroidLog 实时模板配置

There isn't anything broken in your configuration, but if you want to make these Live Templates available for Kotlin you will need to add new Live Template for AndroidLog and make them applicable to Kotlin code.

https://www.jetbrains.com/help/idea/2017.1/creating-and-editing-live-templates.html

There's an open feature request to have them added as defaults here: https://youtrack.jetbrains.com/issue/KT-10464

Change the scope of the template in the applicable option.

在此处输入图片说明

In Android Studio 4.0 there's new AndroidLogKotlin block. You can implement @LeoDroidcoder's solution there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM