CodeBlanks Logo Icon CodeBlanks

Summary - Packages

Combine package, import and internal to set up a module structure.

Summary - Packages

In this group you learned declaring a namespace with package, importing types with import, module visibility with internal, build management with Gradle and the kotlinx extension libraries.

Now you will combine them: put package and import in a file to use File, then define an internal class. This structure is the organizational foundation of Kotlin projects. Later, modular architecture and version catalogs build on it.

Practice Combine package and import

At the top write package com.example.app. Then add import java.io.File. In main create a File with val f = File("kayit.txt") and print it with println(f).

Starter code

Main.kt
// package: com.example.app
// import the java.io.File class
// main: create a File object (path kayit.txt) and println
fun main() {
    // write here
}

Sample solution

Main.kt
package com.example.app

import java.io.File

fun main() {
    val f = File("kayit.txt")
    println(f)
}

Expected output

kayit.txt

Practice Combine internal class and package

At the top write package com.example.tools. Then add import java.io.File. Define internal class Helper; inside it add fun info(f: File): String = f.toString(). In main create an instance with val h = Helper() and print the result with println(h.info(File("kayit.txt"))).

Starter code

Main.kt
// package: com.example.tools
// import java.io.File
// Define Helper as internal; info method returns the path of f
// main: create a Helper instance, call info and println
fun main() {
    // write here
}

Sample solution

Main.kt
package com.example.tools

import java.io.File

internal class Helper {
    fun info(f: File): String = f.toString()
}

fun main() {
    val h = Helper()
    println(h.info(File("kayit.txt")))
}

Expected output

kayit.txt

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which provides module-level visibility?

  • internal Correct answer
  • protected
  • public
  • private

Explanation: internal restricts a definition to the same module.

2 Match the package concepts

Term Meaning
package Namespace
import Bringing in
internal Module visibility
kotlinx Extension libraries

All lessons in Intermediate