Kotlin max()
Published Oct 20, 2023Updated Oct 24, 2023
Contribute to Docs
In Kotlin, the max() function is used to return the greater of two given values provided as arguments. It can be used with numeric types such as Double, Float, Int, Long, UInt, and ULong. Both values must be of the same type.
Note: The
max()function is different from themaxOf()function that can take one or more than two arguments. Ifmax()is used with more or less than two arguments the program will raise an error.
Syntax
import kotlin.math.*
val greatestVal = max(x, y)
- Where
xandyrepresent two numeric values of the same type.
Example
The following example shows the usage of max() comparing two Long values:
import kotlin.math.*fun main() {val longValue1: Long = 9223372036854775807Lval longValue2: Long = 9222372036854775807Lval greatestValue = max(longValue1, longValue2)println("The greater value is: $greatestValue")}
Output:
The greater value is: 9223372036854775807
- In the above example,
longValue1andlongValue2are both of typeLong. The L at the end of the numbers is optional and indicates that these are long literals.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Kotlin on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn Kotlin, the expressive, open-source programming language developed by JetBrains.
- Beginner Friendly.9 hours