A case that feels quite inconvenient when we have many classes with the same name but different packages. Only 1 class will be supported to import for you. Classes with the same other name, if you want to use it, will have to type its full package reference. This makes the code look quite verbose as well as take more time.
Kotlin provides key aliases to solve this problem. In essence, alias will provide an alternate name for a reference to your class. As in the above case, instead of typing the whole package, we just use an alternate name defined briefly.
1 2 3 | typealias PresenterUtils = com.dattien.demo.presenter.utils.Utils |
In the above example we have defined the class Utils at package com.dattien.demo.presenter.utils with the name PresenterUtils .
From now on, just call PresenterUtils without typing the long reference and still not be conflicted with other classes utils at other levels like com.dattien.demo.domain.utils.Utils or com.dattien.demo.data. utils.Utils
1 2 | Lưu ý là các đoạn def với alias được đặt ở mọi file trong project nhưng phải ở bên ngoài class |
Some other examples
1 2 | typealias MapIntToList = HashMap<Int, List<String>> |
and use the following:
1 2 | val map = MapIntToList() |
Alias for inner classes and interfaces
1 2 3 4 5 6 7 8 9 | class DemoClass { interface ViewHolderCallback inner class CustomViewHolder } typealias ViewHolderCallbackInner = com.dattien.demo.presenter.DemoClass.ViewHolderCallback typealias CustomViewHolderInner = com.dattien.demo.presenter.DemoClass.CustomViewHolder |
Distinguish resources
1 2 3 4 5 | typealias AndroidColors = android.R.color typealias ProjectColors = R.color ContextCompat.getColor(this, ProjectColors.colorPrimary) ContextCompat.getColor(this, AndroidColors.black) |
This article is quite brief. Hopefully, this tip can be helpful for making your code more convenient. Happy coding!