can contain newlines and arbitrary text. val str = “Welcome to Kotlin Everywhere \n” val text = “”” for (a in “nenne”) Print a “”” Escaped Strings & Raw Strings
= “Another String” // This works str = true // Error! Boolean value cannot be in string variable str = 14 // Error! Int value cannot be in string variable
or more secondary constructors. class Car(brand: String){ //primary constructor in class header init{ //initializer block print("The car brand is $brand") } constructor(color: String, brand: String) : this(brand){ //secondary constructor print("In the secondary constructor of a $color $brand car") } } Constructors
a function from another class: val myCar = Car("Toyota") myCar.paintOurCar("red") Calling a function from the same class: paintOurCar("red") Functions fun changeCarColor(color: String): String { return "Our car is now $color" }
Greeting { class NestedGreeting { fun greet(){ print( “Hello, how’s it going?” ) } } } Calling the nested class Greeting.NestedGreeting(). greet() Nested classes
able to access members of the outer class class Greeting { private val welcomeMsg = “Hello, how’s it going? ” inner class NestedGreeting { fun greet(){ print( welcomeMsg) } } } Calling the inner class Greeting().NestedGreeting(). greet() Inner classes
open fun play () { print("Yay. Let's play chess.") } } class SecondClass: FirstClass() { fun aFunction() { print("This is a function") } } fun main() { var sampleObject = SecondClass() sampleObject.play() //OUTPUT: Yay. “Let’s play chess } o Inheritance
open fun play () { print("Yay. Let's play chess.") } } class SecondClass: FirstClass() { override fun play() { print("Chess is boring. Let's play checkers") } } fun main() { var sampleObject = SecondClass() sampleObject.play() } o Inheritance
open fun play () { print("Yay. Let's play chess.") } } class SecondClass: FirstClass() { override fun play() { print("Chess is boring. Let's play checkers") } } fun main() { var sampleObject = SecondClass() sampleObject.play() //OUTPUT: Chess is boring. Let’s play checkers } o Inheritance
String, val email: String) The equals(), hashCode(), toString(), copy() and componentN() functions are added automatically. Using the “copy” function val olduser = User("Nenne", "Nwodo", "adoranwodo", "[email protected]") val newuser = olduser.copy(firstname = "Adora") Kotlin
to have at least one parameter e.g. data class User(val firstname: String) • All primary constructor parameters need to be marked as val or var • Data classes cannot be abstract, open, sealed or inner;
"Nwodo", "adoranwodo", "[email protected]") val firstname = user.firstname val lastname = user.lastname val username = user.username val email = user.email print("$firstname $lastname is user $username and their email is $email")