Jim Clermonts
Jim Clermonts

Reputation: 2640

How to shorten imports in Android Studio for cleaner code

Is there an easy shortcut in Android Studio to refactor this:

@GET(WSConstants.ENDPOINT_SINGLE_ACCOUNT)
suspend fun getAccount(@Path(WSConstants.PARAM_ACCOUNT_ID) accountId: String?): Call<Account>

to:

@GET(ENDPOINT_SINGLE_ACCOUNT)
suspend fun getAccount(@Path(PARAM_ACCOUNT_ID) accountId: String?): Call<Account>

And secondly, is it considered good practice? I think it looks cleaner.

Upvotes: 4

Views: 628

Answers (3)

aminography
aminography

Reputation: 22832

AFAIK there is no straightforward solution to do what you want. So:

Solution #1

Click on the each field, for example ENDPOINT_SINGLE_ACCOUNT, and press Alt+Enter, then press on the first option which is Add import for .... It replaces all occurrences of the selected field with the desired notation in the current file.


Solution #2

The briefest way to do so is to use wildcard imports (*) while importing multiple fields. It'd be the highest level of contraction.

import your-package.*

To gain the benefit of this brevity, first, pull out your constants from the object class and put them into a kotlin file:

WSConstants.kt

package your-package

const val ENDPOINT_SINGLE_ACCOUNT = "..."
const val PARAM_ACCOUNT_ID = "..."

Then

  1. Press Ctrl+Shift+R to open the Replace in Path window

  2. Enable regex by pressing .* at the right of the window

  3. Replace WSConstants[.*] with an empty string to remove WSConstants. patterns in the classes

replace WSConstants

enter image description here


Additional:

To define your own policy to organize imports, you can do it from:

File > Settings > Editor > Code Style > Kotlin > Imports (Tab)

Upvotes: 1

Nima Owji
Nima Owji

Reputation: 665

There is no import aliasing mechanism in Java. You cannot import two classes with the same name and use both of them unqualified.

Import one class and use the fully qualified name for the other one, i.e.

import com.text.Formatter;

private Formatter textFormatter;
private com.json.Formatter jsonFormatter;

Upvotes: 0

Rustam Samandarov
Rustam Samandarov

Reputation: 882

When importing write full path of the static variables. For example:

import my.package.name.WSConstants.ENDPOINT_SINGLE_ACCOUNT
import my.package.name.WSConstants.PARAM_ACCOUNT_ID

Upvotes: 2

Related Questions