classes

15 0 0
                                        

syntax:

class Name(var param1: type){

     var field1: type

     fun methodName(): type{

     }

}

A class is a blueprint of an object. For example a bicycle, the class is the design of the bicycle but the object is the real bicycle product you produced. When creating a class, it starts with the keyword class followed by the name of the class followed by the class parameter. Don't worry about constructor first since kotlin compiler automatically creates the constructor for you. A class can have a field and a method. A field is a global variable of your class where it is sometimes link to the parameter of your class. A method is function of your class.

===============

fun main(){

     val degree = Temperature(100.0)

     degree.convertingToCelsius()

}

class Temperature(var fahrenheit: Double){

     fun convertingToCelsius(){

          val celsius = ((fahrenheit - 32)*5)/9

          println("${fahrenheit}°f is ${celsius}°c")

     }

}

===============

Result:

100°f is 37.777777778°c


Note: 

1. The class Temperature has one parameter which is a type Double and has one method that implicitly returns nothing. So, the compiler can tell that the function returns a Unit. There is no need to specify. Inside the method is the computation of fahrenheit to degree celsius. And the result was printed. The println uses a ${}. A dollar sign followed by braces is used when you want to include an expression or a variable inside a string. A degree symbol is alt0176.

2. Inheritance of the class will not be discuss in here. But there was a hint that if you want your class to be inherited, you need to add a keyword open before the class keyword. And when you extend it, you just used a colon after the class parameter which unlike in java, we uses an extends keyword.

================

open class Animal{

}

class LandAnimals(var name: String): Animal{

================

Kotlin ProgrammingWhere stories live. Discover now