Updated March 29, 2023
Introduction to Kotlin Unit
Kotlin unit is one of the return types and it returns null as the value similar to void but Unit is used to return type of any function that does not return any values and it is the optional one so the values are mentioned as the Unit in the return type apart from void Unit is the real class and is also called as Singleton so with only one instance is acceptable for accessing the application wherever its needed unit also the kotlin library so that unit will be applicable for argument type of the one value.
Syntax of Kotlin Unit
Kotlin has many default keywords, classes and methods for implementing the application. Like that unit is one of the class types and it is used in the object class which means it is in the singleton class having only one object.
interface name<T>
{
--some method declarations---
}
class name1:name<Unit>{
---method overridden and declarations—
}
The above codes are the basic syntax for to utilising the unit keyword and it is used in the return type of the classes and functions on the script.
How does Unit work in Kotlin?
The unit in kotlin it corresponds to the void return type which is similar to the java language. Generally, void means it returns null has the value and it passed as the argument type and return type. Unit is the return type of any function that does not return any meaningful values and it is optional to mention the Unit as the return type in the kotlin functions.
Mostly unlike void as the return type and unit is the real class which is mentioned as the singleton instance with only one instance for to call entire areas in the application. And also Unit is equivalent to the void type in the java language so we can explicitly add the unit as the return type for functions that returns null as the value and argument which is used with the other areas of the kotlin codes.
Mainly the Unit class can’t extend with other types and classes which is needed or not there is no option to perform this feature so it fully acts as the private modifiers. So that Unit is the default return type and it is declared as the optional therefore the function is also valid and calls in other areas. The unit has executed all types of jvm and js for common types with only one value using the Unit object.
Examples of Kotlin Unit
Given below are the examples mentioned:
Example #1
Code:
class States(val statename : String, val statecapital : List<Tourist>)
class Tourist(val touristname : String, val touristcities : List<String>)
class TouristMonths {
val mnths = listOf("January", "February","March","April","May","June","July","August","September","October","November","December")
val elects = listOf("Ups","Inverters","Gadgets","Desktop PCs","Microwave Oven","Fridge","Washing Machine","mobile")
val lap = listOf("Dell latitude", "dell inspiron","sony","acer","samsung","lenovo","apple")
val placesvisited = listOf(
States("Delhi", listOf(Tourist("Noida", lap),
Tourist("Darjeeling", mnths))),
States("Tamilnadu", listOf(Tourist("Chennai", elects))))
}
data class Customers(
val custname: String,
val custid: Int
)
enum class Banks (
val names: String, val id:Int, val sno:Int
) {
First("PNB",1,123), Second("IOB",2,466),
Third("SBI",3,7898), Four("RBL",4,7885), Five("Indian",5,798),
Six("Indusland",6,124453), Seven("HDFC",7,984);
}
fun operations(): Unit {
println("Your kotlin unit first example ")
}
fun main (args: Array<String>) {
println("Welcome To My Domain your listed banks are as follows:")
operations()
var trt=TouristMonths()
trt.placesvisited.forEach { c -> println(c.statename) }
println("#############################################################")
println("Welcome To My Our tourist services")
println("Its the first example that related to the kotlin Unit example")
println("#############################################################")
println("First we passed the input as Arrays")
val arnum = arrayOf(8, 3, 4, 2,1,5,9,7,6)
arnum.forEach { println(it) }
val usr = arrayOf(Customers("sivaraman", 32),
Customers("raman", 23),
Customers("arunkumar", 16))
usr.forEach { println(it) }
println("We used forEach loop for handling collection datas")
val inp = listOf(1, 4, 3, 2)
inp.forEach{println(it)}
val numusras = listOf(Customers("xx", 42),
Customers("yy", 44),
Customers("xx zz", 46))
numusras.forEach { println(it) }
println("We used forEach loop with collection class called HashMap and its methods")
val hshmap = hashMapOf(32 to "kunju", 12 to "moanan", 54 to "sevela" )
hshmap.forEach{ println(it) }
val map2 = hashMapOf("kumar" to Customers("kumar", 15),
"arun" to Customers("arun", 16),
"arun kumar" to Customers("arun kumar", 16))
map2.forEach{ println(it) }
}
Output:
In the above example, we used kotlin codes but return type as Unit on the output console screen. Here we used some enums, classes and classes like collections. Using enums we can declare the values and utilised the values in the main method wherever requires. The list interface is the collection interface and it stores and retrieves the datas.
Example #2
Code:
val mnthstrs = "January is the first month, February is the second month, march is the third month, april is the fourth month, may is the fifth month, june is the sixth month, july is the seventh month, august is the eight month, September is the ninth month, october is the tenth month, November is the eleventh month, december is the twelth month"
fun operations(): Unit {
println("The month details are: " + mnthstrs)
}
fun main() {
println("Welcome To My Domain its the second example that related to the kotlin unit")
operations()
}
Output:
In the second example we used Kotlin Unit as the Type to avoid the return values as Unit. And we can implement the Unit as the operations() method and it will call in the main.
Example #3
Code:
fun firstMethod(str:String): Unit{
println("Your first kotlin method for the Unit concept")
println(str)
}
fun secondMethod( str1 : String, demo: (String) -> Unit){
println("Your second method for the Unit")
demo(str1)
}
fun main(args: Array<String>) {
println("Welcome To My Domain its the third example that related to the kotlin Unit")
secondMethod("Your input key is string: Thank you users for spending the time",::firstMethod)
}
Output:
In the final example, we used Unit type to convert the values to the string type. Here we used both Unit and another datatype as the parameter and it will call in the main.
Conclusion
In kotlin language has a lot of concepts and features for implementing the applications with more sophisticated. Like that Unit is one of the kotlin concepts and it is used in the various areas of the script and it combines with the other data types to perform the user operations in the task.
Recommended Articles
This is a guide to Kotlin Unit. Here we discuss the introduction, syntax, and working of a unit in kotlin along with different examples for better understanding. You may also have a look at the following articles to learn more –