Kotlin: Kotlin File vs Class. Whats the difference?

Kotlin Programming

Question or issue of Kotlin Programming:

Just started using Kotlin and created some activities as Kotlin Files. They work, but still, I want to know what the difference between creating a File and a Class.

How to solve this issue?

Solution no. 1:

icon Kotlin Class: Android Studio displays it with no extension if the file contains ONLY ONE class.

Unlike Java, Kotlin allows you to put certain things outside the class like:

  • extension functions
  • constants

If you, therefore, add any of the above or another class to the file, Android Studio will change it to “Kotlin File”:

icon with extension .kt

Removing the above extras, will again show the file as “Kotlin Class”

Solution no. 2:

The only difference is that creating a file creates a file with no classes, and creating a class creates a file with one class. You can then add more classes to the file, or delete classes, or make any other changes – the end result doesn’t depend on how the file was created.

Solution no. 3:

Here is the answer from the official Documentation:

If a Kotlin file contains a single class (potentially with related
top-level declarations), its name should be the same as the name of
the class, with the .kt extension appended. If a file contains
multiple classes, or only top-level declarations, choose a name
describing what the file contains, and name the file accordingly. Use
camel humps with an uppercase first letter (e.g.
The name of the file should describe what the code in the file does.
Therefore, you should avoid using meaningless words such as “Util” in
file names.

so basically a file can -for instance- contains just (helper-)functions without any class declaration.

Solution no. 4:

As I can see Kotlin file has many classes inside it But a Kotlin class has one class with that name, that’s only an observation though.

Solution no. 5:

Yes, if you define more than one class, it will be automatically converted to file, otherwise it will be automatically converted to class. Usually I think if you need to define some variables or methods that can be directly referenced, you can put them in the file.

Hope this helps!