From the course: Build Spring Boot Apps with the Kotlin Programming Language
Unlock this course with a free trial
Join today to access over 22,600 courses taught by industry experts.
Secondary constructors
From the course: Build Spring Boot Apps with the Kotlin Programming Language
Secondary constructors
- [Instructor] Now when we have a default constructor, we can provide alternative constructors if we want to. These are known as secondary constructors. For example, suppose we're happy for the address to be an empty string if it's not known. We could provide a secondary constructor which allows us to do this. So in here, we create a constructor. We say what other parameters we're going to pass into this constructor. Well it's going to be a name which is a string and it's going to be an age which will be an integer but there will be no address. Note that when we define our constructor, and this applies whether it's a single constructor or multiple constructors, we don't don't put in val or var before our variable names as the parameters. This effectively is a function and as we saw in the chapter on functions, by default all the variables you pass into a constructor are vals. You can't change that. You don't put the keyword in. So the name and the age that we're providing in here…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.
Contents
-
-
-
-
-
-
-
(Locked)
Project structure and packages2m 5s
-
(Locked)
The class declaration and class-level attributes3m 31s
-
Instantiating a class and accessing class-level attributes2m 14s
-
(Locked)
Creating a simple constructor5m 7s
-
(Locked)
Secondary constructors5m 20s
-
(Locked)
Alternative class design5m 3s
-
(Locked)
Overriding getters and setters7m 21s
-
(Locked)
Functions within a class2m 57s
-
(Locked)
Static functions3m 28s
-
(Locked)
Data classes7m 32s
-
(Locked)
-
-
-
-
-
-
-
-
-
-
-
-
-
-