Kotlin File vs Class. Whats the difference?

FileClassKotlin

File Problem Overview


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.

File Solutions


Solution 1 - File

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 2 - File

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 3 - File

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. > ProcessDeclarations.kt). > > 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 4 - File

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 5 - File

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.

Solution 6 - File

The difference is:

  • Kotlin Class can have only a class.

  • Kotlin File can have many classes.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVlad SkurtolovView Question on Stackoverflow
Solution 1 - FileyoleView Answer on Stackoverflow
Solution 2 - FileMaciej BeimcikView Answer on Stackoverflow
Solution 3 - FilekorchixView Answer on Stackoverflow
Solution 4 - Fileuser2734915View Answer on Stackoverflow
Solution 5 - FileFoAngView Answer on Stackoverflow
Solution 6 - FileNamelessView Answer on Stackoverflow