Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

A collection of random and frequently used idioms in Kotlin.

NotificationsYou must be signed in to change notification settings

geekonjava/KotlinIdiom

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 

Repository files navigation


type: doclayout: referencecategory: "Basics"title: "Idioms"

Idioms

A collection of random and frequently used idioms in Kotlin. If you have a favorite idiom, contribute it by sending a pull request.

Creating DTOs (POJOs/POCOs)

data classCustomer(valname:String,valemail:String)

provides aCustomer class with the following functionality:

  • getters (and setters in case ofvar{: .keyword }s) for all properties
  • equals()
  • hashCode()
  • toString()
  • copy()
  • component1(),component2(), ..., for all properties (seeData classes)

Default values for function parameters

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

Filtering a list

val positives= list.filter { x-> x>0 }

Or alternatively, even shorter:

val positives= list.filter { it>0 }

String Interpolation

println("Name$name")

Instance Checks

when (x) {isFoo->...isBar->...else->...}

Traversing a map/list of pairs

for ((k, v)in map) {println("$k ->$v")}

k,v can be called anything.

Using ranges

for (iin1..100) {... }// closed range: includes 100for (iin1 until100) {... }// half-open range: does not include 100for (xin2..10 step2) {... }for (xin10 downTo1) {... }if (xin1..10) {... }

Read-only list

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

Read-only map

val map=mapOf("a" to1,"b" to2,"c" to3)

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 and else shorthand

val files=File("Test").listFiles()println(files?.size?:"empty")

Executing a statement if null

val data=...val email= data["email"]?:throwIllegalStateException("Email is missing!")

Execute if not null

val data=...data?.let {...// execute this block if not null}

Map nullable value if not null

val data=...val mapped= data?.let { transformData(it) }?: defaultValueIfDataIsNull

Return on when statement

funtransform(color:String):Int {returnwhen (color) {"Red"->0"Green"->1"Blue"->2else->throwIllegalArgumentException("Invalid color param value")    }}

'try/catch' expression

funtest() {val result=try {        count()    }catch (e:ArithmeticException) {throwIllegalStateException(e)    }// Working with result}

'if' expression

funfoo(param:Int) {val result=if (param==1) {"one"    }elseif (param==2) {"two"    }else {"three"    }}

Builder-style usage of methods that returnUnit

funarrayOfMinusOnes(size:Int):IntArray {returnIntArray(size).apply { fill(-1) }}

Single-expression functions

funtheAnswer()=42

This is equivalent to

funtheAnswer():Int {return42}

This can be effectively combined with other idioms, leading to shorter code. E.g. with thewhen{: .keyword }-expression:

funtransform(color:String):Int=when (color) {"Red"->0"Green"->1"Blue"->2else->throwIllegalArgumentException("Invalid color param value")}

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

classTurtle {funpenDown()funpenUp()funturn(degrees:Double)funforward(pixels:Double)}val myTurtle=Turtle()with(myTurtle) {//draw a 100 pix square    penDown()for(iin1..4) {        forward(100.0)        turn(90.0)    }    penUp()}

Java 7's try with resources

val stream=Files.newInputStream(Paths.get("/some/file.txt"))stream.buffered().reader().use { reader->println(reader.readText())}

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

//  public final class Gson {//     ...//     public <T> T fromJson(JsonElement json, Class<T> classOfT) throws JsonSyntaxException {//     ...inlinefun <reifiedT:Any> Gson.fromJson(json:JsonElement):T=this.fromJson(json,T::class.java)

Consuming a nullable Boolean

val b:Boolean?=...if (b==true) {...}else {// `b` is false or null}

[8]ページ先頭

©2009-2025 Movatter.jp