기본 콘텐츠로 건너뛰기

Kotlin Grammar

Kotlin is a programming language developed by Jetbrain.
It was first published in 2011, but Kotlin has got the fame very slowly.
The most significant factor in Kotlin, I think, is that it can deal with null exception safely.


Using Kotlin in Android Studio

Install Kotlin Plugins

  • Ctrl + Shift + A.
  • Put ‘convert java file to kotlin’.
  • Ctrl + Shift + A again.
  • Put ‘sync project with gradle files’
  • Click ‘configure’ in upper right side of the screen.
  • Click OK.

Basis

Variable Declaration

val, var

  • val : constant // It may mean VALue or VAriable Literal I think…
  • var : variable

data type

  • with colon
    • val age : Int = 25

etc

  • And it doesn’t use semi colons.

Functions

basic format

fun add(a: Int, b: Int): Int {
    return a + b
}

simple format

fun add(a: Int, b: Int): Int = a + b
fun max(a: Int, b: Int): Int = if (a > b) a else b

Null Safety

? (nullable)

  • In default, Kotlin doesn’t permit to put null into variables.
  • If we encounter a case that we have to use null, then we can use nullable signature which is written as ‘?’.
var a: Int = 15
a = null        // error!
var b: Int? = 15
b = null        // It works.

?. (safe calls)

  • It calls the member or the method only when the object is not null
fun getSize(targetStr: String?): Int? {
    return targetStr?.length    // If targetStr is null, targetStr?.length returns null.
}
  • It simplifies code like this
if(aaa != null && bbb != null && ccc != null) {
    return aaa.bbb.ccc.name;
}
return null;

into

return aaa?.bbb?.ccc?.name

Any & is

Any

  • It’s same with Object in Java.

is

  • It’s same with instanceof in Java.

usage example

fun getStringLength(obj: Any): Int? {
    if(obj is String) {
        return obj.length
    }
    return null
}

when

  • example
fun main(args: Array<String>) {
    cases(2)
    cases(4)
}

fun cases(obj: Any) {
    when(obj) {
        1 -> println("white balloon flower")
        2 -> println("circular record")
        3 -> println("blue water parsely")
        4 -> println("pretty blue bird")
    }
}
  • execution result

circular record
pretty blue bird

ranges

usage in loop

for (x in 1..10) {  // 1 <= x <= 10
    println(x)
}

usage in if (with ‘in’)

val array = arrayList<String>
array.add("aaa")
array.add("bbb")

val x = 3

if(x !in 0..array.size - 1) {
    println("Out: array size is ${array.size}, but you requested x = ${x}")

Idioms

Class

getters and setters

  • Unlike Java, no need to make them.
  • example
var sample: Sample = Sample("Name", "a@a.c")
println(sample.name)
println(sample.email)

Data Class

It is the class that is just holding data, without any methods.

format

data class User(val name: String, val age: Int)

requirements

  • The primary constructor needs to have at least one parameter.
  • The parameters should be marked as ‘var’ or ‘val’.
  • Data classes cannot be abstract, open(public), sealed(private) or inner

built-in functions

  • equals(), hashCode()
  • toString()
    • It returns like this : “User(name=John, age=42)”
  • componentN() // I don’t know what it is :)
  • copy()
    • This method can be used when we need to copy an object with changing only some of its property.
    • example
val jack = User(name="Jack", age=1)
val olderJack = jack.copy(age=2)

Lambdas

definition and features

  • definition
    • A “function literal” or an “anonymous function”
  • features
    • Its parameters are declared before ->, and the body goes after ->.
    • A lambda expression is always surrounded by curly braces({ }).
      ex) {a, b -> a.length < b.length}

example

  • Java code
button.setOnClickListener {
    public void onClick(View view) {
        view.setAlpha(0.5f);
    }
}
  • Java lambda code
button.setOnClickListener {
    view -> view.setAlpha(0.5f);
}
  • Kotlin lambda code (original grammar)
button.setOnClickListener {
    view -> view.setAlpha(0.5f)
}
  • Kotlin lambda code (modified grammar (it))
    • We can use ‘it’ only if the number of parameters is 1.
button.setOnClickListener {
    it.alpha = 0.5f
}
// it = 그 메소드에 파라미터로 넘긴 그거 (IT that is given to the method as a parameter)

Filters

filter

  • Java code
for (Integer intger : list) {
    if(integer < 10) {
        integer *= 2;
    }
  • Kotlin code
list.filter { it < 10 }.map { it *= 2 }

filterNotNull

val listWithNull = List<Int?> = listOf(1, 2, null, 3, 4, 5)
val listWithoutNull = listWithNull.filterNotNull()
listWithoutNull.map{ 
    Log.d("TAG", "NotNULL it " + it) 
}

filterNot

val listWithNull = List<Int?> = listOf(1, 2, null, 3, 4, 5)
listWithNull.filterNot{ it == null }.map {
    Log.d("TAG", "NotNULL it " + it) 
}

String Interpolation

$variableName

val a: String = "name"
val b: String = "Sejin"
Log.d("TAG", "$a: $b") 

Data Structure Declaration (~Of)

arrayOf

var numbers: Int = intArrayOf(1, 2, 3, 4, 5)

listOf

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

mapOf

It uses keyword ‘to’.

val map = mapOf("A" to 1, "B" to 2, "C" to 3)

Infix Notation

It’s a magic T_T…

fun Int.multiply(x: Int): Int {
    return this * x
}

The code above is adding a new method ‘multiply(x: Int): Int’ to ‘Int’ class.
So from now on, we can use multiply method like below.

val mulResult = 3.multiply(10)

In addition, we can use this multiply into inflix notation form.

val mulResult = 3 multiply 10



I mainly refered to here.

댓글

이 블로그의 인기 게시물

The reason why I selected Google Blogger

In SW Maestro, 3 mentors for our team are fixed, and we got our first official mentoring from mentor 배권한. He gave us an assignment - make a personal blog and post an article about co-working tools. He insisted we run a blog for 4 reasons. We forget what we have studied someday We can realize something new when we think about it again Somebody like a headhunter may contact me through my blog To make my activities visible So, I decided to make a post about pros and cons of famous blog services. Criteria of Selection I consider these factors. Main Factors It should 'work' well. It should be easy to parse my posts from the blog. It should be easy to write code on my blog. It must take responsive design, so that it can be seen with mobile device. It must be easy to be exposed by Google search. It must provide reply function. Sub Factors It is good if the design is fine. It is good if the markdown function is...

Running Anaconda Python on Jupyter Notebook with Docker in Windows

I think there is no IDE more suitable for studying machine learning or deep learning with Python than Jupyter Notebook. However, it is so difficult to construct a Jupyter environment without crushing with the existing Python environment. So, I decided to make an only-for-deep-learning environment in the Ubuntu Docker container to avoid all annoyance. I will assume that you already installed Docker. Environment Ubuntu 17.04 LTS Anaconda 5.0.0 (containing Python 3.6) Creating Docker Container First of all, we are going to create a Docker container. The world is going better day after day! You can get a Docker image containing Anaconda that someone created and simultaneously make a container with the image you just downloaded just with this one-line command. docker run - it --name jupyter -p 8000:8000 --volume /c/Users/jinai/Dropbox/HaveToLearnToRun/CSE/3_1_MachineLearning/jupyter_workspace:/root/jupyter_workspace continuumio/anaconda3 /bin/bash It’s quite complex. So let m...

Neural Network [cs231n - week 3 : Loss Functions and Optimization]

The purpose of this post is to summarize the content of cs231n lecture for me, so it could be a little bit unkind for people who didn’t watch the video . In addition, I omitted some contents that I don’t think it’s important enough, so use this article as just an assistance. Loss Function Below is the general numerical expression of loss functions. Multiclass SVM Loss There are many many many kinds of loss functions, but this class only deals with two of them : SVM loss and softmax . Above is the expression of SVM loss function. Meaning of the expression is, that score of the correct class should be larger at least one comparing to scores of the others to make the loss zero. It is more easier to understand it with an example. First, get each loss of the class like the image above. I'm not omitting the explanation because it's annoying to write. It's because explanation of the lecture slide is kind enough. And then, get the loss by calculating the mean va...