0
0
Kotlinprogramming~5 mins

Class declaration syntax in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the basic syntax to declare a class in Kotlin?
Use the <code>class</code> keyword followed by the class name and curly braces. Example: <pre>class MyClass { }</pre>
Click to reveal answer
beginner
How do you declare a primary constructor in a Kotlin class?
Add the constructor parameters directly after the class name in parentheses. Example: <pre>class Person(val name: String, var age: Int)</pre>
Click to reveal answer
beginner
What keyword is used to declare a class in Kotlin?
The keyword is class. It tells Kotlin you are defining a new class.
Click to reveal answer
beginner
Can a Kotlin class have no body? Show an example.
Yes, if there is no need for properties or functions inside, you can omit the curly braces. Example: <pre>class Empty</pre>
Click to reveal answer
beginner
How do you declare properties inside a Kotlin class primary constructor?
Use <code>val</code> for read-only and <code>var</code> for mutable properties inside the constructor parentheses. Example: <pre>class Car(val brand: String, var year: Int)</pre>
Click to reveal answer
Which keyword starts a class declaration in Kotlin?
Aclass
Bstruct
Cobject
Dfun
How do you declare a primary constructor with two properties in Kotlin?
Aclass Person(name: String, age: Int)
Bclass Person(val name: String, var age: Int)
Cclass Person { val name: String; var age: Int }
Dfun Person(val name: String, var age: Int)
Can a Kotlin class be declared without curly braces?
AOnly if it has a primary constructor
BNo, curly braces are always required
CYes, if the class has no body
DOnly for abstract classes
What does val mean in a Kotlin class constructor?
ARead-only property
BMutable property
CFunction parameter
DLocal variable
Which of these is NOT a valid Kotlin class declaration?
Aclass Animal(val species: String)
Bclass Vehicle { val wheels = 4 }
Cclass Book(var title: String, var author: String)
Dclass Person function(name: String)
Explain how to declare a simple Kotlin class with a primary constructor that has two properties.
Think about how you write the class name and put properties inside parentheses.
You got /4 concepts.
    Describe when you can omit the curly braces in a Kotlin class declaration.
    Consider if the class has no properties or functions inside.
    You got /3 concepts.