Kotlin Class: MathConstants object for Mathematical constants
Write a Kotlin program that creates an object declaration 'MathConstants' that provides constants for mathematical calculations such as PI and E.
Pre-Knowledge (Before You Start!)
Before attempting this exercise, you should be familiar with the following concepts:
- Object Declarations: In Kotlin, an object declaration creates a singleton, meaning only one instance of the object exists.
- Constants in Kotlin: Using val to define immutable values.
- Accessing Object Properties: Accessing properties of an object using objectName.propertyName.
- Printing Values: Using println() to output values to the console.
Hints (Try Before Looking at the Solution!)
Try to solve the problem using these hints:
- Hint 1: Declare an object named MathConstants instead of a class.
- Hint 2: Inside the object, define two constants, PI and E, using val.
- Hint 3: In the main() function, access the constants using MathConstants.PI and MathConstants.E.
- Hint 4: Print the values of PI and E using println().
Sample Solution:
Kotlin Code:
object MathConstants {
val PI = 3.14159
val E = 2.71828
}
fun main() {
println("Value of PI: ${MathConstants.PI}")
println("Value of E: ${MathConstants.E}")
}
Sample Output:
Value of PI: 3.14159 Value of E: 2.71828
Explanation:
In the above exercise -
- First we define an object declaration "MathConstants" which serves as a singleton object. Inside the MathConstants object, we define two properties PI and E to hold mathematical constants.
- In the "main()" function, we access PI and E values using the MathConstants object and print them.
Kotlin Editor:
Previous: Inline class email for type-safe email address representation.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics