#5 Exploring Kotlin -Package

Arun Pandian M
2 min readFeb 15, 2020

--

As we know, Packages usually use to group the related classes. Like Java, Kotlin file also may start with a package declaration but with just a few additions/improvements.

Declaration:

  • Like java, we can declare the package name using package keyword
  • Package statements are just like Java, but they don’t have to match the directory the file is in
  • let me explain the above concept using the below picture
  • In the first picture, the java package name doesn’t match with corresponding file path show it shows error
  • In the second picture, the java package name doesn’t match with directory the file is in. so it doesn’t show the error while declaring the package name
  • In the third picture, the kotlin package name doesn’t match with the directory the file is in. but it doesn’t show the declaration error in kotlin

Imports:

  • If the package is not specified, the contents of such a file belong to the default package that has no name.
  • The import statement is not restricted to only importing class. It can be a top-level function, enum constants.

Default Import:

A number of packages are imported into every Kotlin file by default:

Additional packages are imported depending on the target platform:

JVM:

JS:

In Kotiln, there is no import static syntax.

With the help of static import, we can access the static members of a class directly without a class name or any object.

Import aliasing

  • In Kotlin, when importing two classes or functions with the same name from different libraries, the class or function name is conflicted. In order to correct the conflict, you have to import one class name with ‘as’ keyword.
package com.arun.sample
import com.arun.sampleTest.SampleKotlin
import com.arun.sample.SampleKotlin as RenamedSampleKotlin // as keyword used to solve the conflict
fun main(args: Array<String>) {
println("Hello World!")
var sampleTestClass1: SampleKotlin = SampleKotlin()
var renameSample:RenamedSampleKotlin =RenamedSampleKotlin()
sampleTestClass1.getKotlinClassFrom()
renameSample.getKotlinClassFrom()

}

If this is good to you, please do hit the clap button ❤ or let me know in the comment. any help related in android touch with me on Twitter.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Arun Pandian M
Arun Pandian M

Written by Arun Pandian M

Senior Android developer at FundsIndia, A time investor to learn new things about Programming. Currently in a relationship with Green Bug(Android).

No responses yet

Write a response