Kotlin – Typealias

Tram Ho

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.

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

Some other examples

and use the following:

Alias ​​for inner classes and interfaces

Distinguish resources

This article is quite brief. Hopefully, this tip can be helpful for making your code more convenient. Happy coding!

Share the news now

Source : Viblo