Kotlin Class: MathConstants object for Mathematical constants
Kotlin Class: Exercise-20 with Solution
Write a Kotlin program that creates an object declaration 'MathConstants' that provides constants for mathematical calculations such as PI and E.
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/kotlin-exercises/class/kotlin-class-exercise-20.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics