본문

170529(월) - Kotlin docs (Idioms)

Kotlin docs


Idioms


Creating DTOs (POJOs/POCOs)

data class Customer(val name: String, val email: String)


- getter (var 일때 setters)

- equals()

- hashCode()

- toString()

- copy()

- component1(), component2()...



Default values for function parameters

fun foo(a: Int = 0, b: String = "") { ... }



Filtering a list

val positives = list.filter {

x -> x > 0

}


val positives = list.filter {

it > 0

}



String Interpolation

println("Name $name")



Instance Checks

when (x) {

is Foo -> ...

is Bar -> ...

else   -> ...

}



Traversing a map/list of pairs

for ((k, v) in map) {

println("$k -> $v")

}



Using ranges

for (i in 1..100) { ... }             // includes 100

for (in in 1 until 100) { ... }     // not include 100

for (x in 2..10 step 2) { ... }     

for (x i 10 downTo 1) { ... }

if (x in 1..10) { ... }



Read only list

val list = listOf("a", "b", "c")



Read only map

val map = mapOf("a" to 1, "b" to 2, "c" to 3)



Accessing a map

println(map["key"])

map["key"] = value



Lazy Property

val p: String by lazy {

// compute the string

}



Extension functions

fun String.spaceToCamelCase() { ... }


"Convert this to camelcase".spaceToCamelCase()




Creating a singleton

object Resource {

val name = "Name"

}



If not null shorthand

val files = File("Test").listFiles()


println(files?.size)



If not null else shorthand

val files  = File("Test").listFiles()


println(files>.size ?: "empty");



Executing a statement if null

val data = ...

val email = data["email"] ?: throw IllegalStateException("Email is missing!")



Executing if not null

val data = ...


data?.let {

...

}



Return on when statement

fun transform(color: String): Int {

return when (color) {

"Read" -> 0

"Green" -> 1

"Blue" -> 2

else -> throw IllegalArgumentException("Invalid color param value")

}

}



try/catch expression

try/catch 도 return 존재


fun test() {

val result = try {

count() 

} catch (e: ArithmeticException) {

throw IllecalStateException(e)

}

}



If expression

fun foo(param: Int) {

val result = if (param == 1) {

"one"

} else if (param == 2) {

"two"

} else {

"three"

}

}



Builder style usage of methods that return Unit

fun arrayOfMinusOnes(size: Int): IntArray {

return IntArray(size).apply {

fill(-1)

}



Single expression functions

fun theAnswer() = 42


fun theAnswer(): Int {

return 42

}



fun transform(color: String): Int = when (color) {

"Read" -> 0

"Green" -> 1

"Blue" -> 2

else -> throw IllegalArgumentException("Invalid color param value")

}



Calling multiple methods on an object instance('with')

class Turtle {

fun penDown()

fun penUp()

fun turn(degrees: Double)

fun forward(pixels: Double)

}


val myTurtle = Turtle()

with(myTurtle) {

penDown()

for(i in 1..4) {

forword(100.0)

turn(90.0)

}


penUp()

}



Java 7's try with resources

val stream = Files.newInputStream(Paths.get("/som/file.txt"))

stream.buffered().reader().use { reader ->

println(reader.readText())

}



Convenient form for a generic function that requires the generic type information

inline fun <reified T: Any> Gson.fromJson(json): T = this.fromJson(json, T::Class.java)



Consuming a nullable Boolean

val b: Boolean? = ...

if (b == true) {

...

} else {

// b is false of null

}


'Mobile > Kotlin' 카테고리의 다른 글

170607(수) - Kotlin docs (Basic Types)  (0) 2017.05.31
170530(화) - Kotlin docs(Coding Conventions)  (0) 2017.05.30
170417(월) - Kotlin docs (Basic Syntax)  (0) 2017.04.17
170410(월) - Kotiln-docs (Basic Syntax)  (0) 2017.04.10
161118(금)  (0) 2016.11.18

공유

댓글