HTML tutorial
CSS3 tutorial
Bootstrap tutorial
JavaScript tutorial
JQuery tutorial
AngularJS tutorial
React tutorial
NodeJS tutorial
PHP tutorial
Python tutorial
Python3 tutorial
Django tutorial
Linux tutorial
Docker tutorial
Ruby tutorial
Java tutorial
C tutorial
C ++ tutorial
Perl tutorial
JSP tutorial
Lua tutorial
Scala tutorial
Go tutorial
ASP.NET tutorial
C # tutorial
You can also use functions inside a class, to perfom certain actions
You can also use functions inside a class, to perfom certain actions:
Create a drive()
function inside the
Car
class and call it:
class Car(var brand: String, var model: String, var year: Int) {
// Class function
fun drive() {
println("Wrooom!")
}
}
fun main() {
val c1 = Car("Ford", "Mustang", 1969)
// Call the function
c1.drive()
}
Tip: When a function is declared inside a class, it is known as a class function, or member function.
Note: When an object of the class is created, it has access to all of the class functions.
Just like with regular functions, you can pass parameters to a class function:
Create two functions: drive()
and speed()
, and pass parameters to the
speed()
function:
class Car(var brand: String, var model: String, var year: Int) {
// Class function
fun drive() {
println("Wrooom!")
}
// Class function with parameters
fun speed(maxSpeed: Int) {
println("Max speed is: " + maxSpeed)
}
}
fun main() {
val c1 = Car("Ford", "Mustang", 1969)
// Call the functions
c1.drive()
c1.speed(200)
}