‘when’ operator in Kotlin

var intNumber = 10
when (intNumber) {
1 -> print(“value is 1”)
2 -> print(“value is 2”)
else -> {
print(“value of intNumber is neither 1 nor 2”)
}
}
This post was originally posted at https://agrawalsuneet.github.io/blogs/when-operator-in-kotlin/ and reposted on Medium on 11th Jan 2018.
fun calculateAreaOfCircle(radius: Float): Float {
return (22 * radius * radius) / 7
}
fun calculateAreaOfSquare(sideLength: Float): Float {
return (sideLength * sideLength)
}
fun calculateArea(shape: Shape) : Float {
var area = when (shape) {
is Circle -> calculateAreaOfCircle( radius = 6f)
is Square -> calculateAreaOfSquare(sideLength = 10f)
else -> {
print(“invalid shape”)
return 0f
}
}
//use area for further use
return area
}
var count = 100
when (count) {
in 0 until 100 -> {
//count is between 1 to 99
count++
}
else -> {
//count is greater than 99
//set it to 0
count = 0
}
}
val boolValue : Boolean = false

when (boolValue) {
false -> {
print(“value is false”)
}
true -> {
print(“value is true”)
}
}
val value = 100

when (value) {
0, 1 -> print(“x == 0 or x == 1”)
!in 10..20, !in 30..40 -> {
print(“not in 10 to 20 and 30 to 40”)
}
else -> print(“otherwise”)
}
 val value = 21
val initialPrimeNumbers = intArrayOf(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47)

when (value) {
in 10..20 -> print(“in 10 to 20”)
!in 30 until 40 -> print(“not in 30 to 39”)
in initialPrimeNumbers -> print(“exist in array”)
else -> print(“not present anywhere”)
}
val shape : Shape = Circle()

when (shape) {
is Circle -> print(“shape is a Circle class object”)
is Square -> print(“shape is a Square class object”)
else -> {
print(“invalid shape”)
}
}
val num = 10
when {
isPrime(num) -> print(“num is a prime number”)
isComposite(num) -> print(“num is a composite number”)
else -> {
print(“num is neither prime nor composit”)
}
}

--

--

--

https://agrawalsuneet.github.io/

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Suneet Agrawal

Suneet Agrawal

https://agrawalsuneet.github.io/

More from Medium

3 Best Practices for Using Named Arguments in Kotlin

Kotlin Collections & Operations

Kotlin Programming Language: Everything You Need to Know

How to Use TriState Toggle in Jetpack Compose