Skip to content

Instantly share code, notes, and snippets.

@jesusbmx
Last active May 30, 2018 20:33
Show Gist options
  • Save jesusbmx/2c87ca170db502b5c34f909b3064ba34 to your computer and use it in GitHub Desktop.
Save jesusbmx/2c87ca170db502b5c34f909b3064ba34 to your computer and use it in GitHub Desktop.
From Java to Kotlin
public class Demo {
public static void main(String[] args){
}
}
class Demo {
fun init() {
print(sum(1,2))
print(sum(1,2))
val items = listOf("apple", "banana", "kiwifruit")
for (item in items) {
println(item)
}
//val items = listOf("apple", "banana", "kiwifruit")
//for (index in items.indices) {
// println("item at $index is ${items[index]}")
//}
}
/**
* Suma 2 enteros
*/
fun sum(a: Int, b: Int): Int {
return a + b
}
/**
* Suma 2 flotantes
*/
fun sum(a: Float, b: Float) = a + b
/**
* Usando expresiones condicionales
*
* fun maxOf(a: Int, b: Int) = if (a > b) a else b
*
*/
fun maxOf(a: Int, b: Int): Int {
if (a > b) {
return a
} else {
return b
}
}
fun usingAForLoop() {
val items = listOf("apple", "banana", "kiwifruit")
for (item in items) {
println(item)
}
// or
for (index in items.indices) {
println("item at $index is ${items[index]}")
}
}
fun usingAWhileLoop() {
val items = listOf("apple", "banana", "kiwifruit")
var index = 0
while (index < items.size) {
println("item at $index is ${items[index]}")
index++
}
}
/**
* Using When Expression
*/
fun describe(obj: Any): String =
when (obj) {
1 -> "One"
"Hello" -> "Greeting"
is Long -> "Long"
!is String -> "Not a string"
else -> "Unknown"
}
fun usingRanges() {
val x = 10
val y = 9
if (x in 1..y+1) {
println("fits in range")
}
}
fun main(args : Array<String>) {
var demo = Demo()
demo.init()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment