출처: https://3months.tistory.com/307 [Deep Play]

4-1/캡스톤디자인

Java VS Kotlin

코딩하는 랄뚜기 2022. 3. 18. 00:39

nullable, nullsafe

 

val b: Int? =100 // nullable
val c: Int = 100 // nullsafe

b?.sum() // null 일 경우 실행하지 않음
c.sum() // 애초에 null safe 함

 

Kotlin은 변수를 선언할 때 null이 들어올 수 있는 nullable 방식과 들어 올 수 없는 nullsafe 방식이 있다.

 


apply

//Kotlin
val person=Person().apply{
    firstName="Fast"
    lastName="Campus"
}
//Java
Person person = new Person();
person.firstName = "Fast";
person.lastName = "Campus";

Apply는 객체생성을 쉽게 해준다.

 

 


also

//Kotlin
Random.nextInt(100).also{ // it으로 람다값 접근
    print("getRandomInt() generated value $it")
}

Random.nextInt(100).also{ value-> // value로 람다값 접근 가능
    print("getRandomInt() generated value $value")
} 

//Java
int value = Random().nextInt(100);
System.out.print(value);

let

//Kotlin
val number: Int? //nullable

val sumNumberStr = number?.let{
   "${sum(10,it)}" //number+10하라는 의미
}.orEmpty() // null이면 empty

//Java
Integer number = null;
String sumNumberStr = null;
if(number!=null){
    sumNumberStr=""+sum(10,number);
}else{
    sumNumberStr="";
}

 


with

//Kotlin
val person = Person()

with(person){
    work()
    sleep()
    println(age)
}

//Java
Person person = new Person();

person.work();
person.sleep();
System.out.println(person.age);

 


run

//Kotlin
val result = service.run{
    port=8080
    query()
}

//Java
service.port = 8080;
Result result=service.query();

 


 

data class

//Kotlin
data class JavaObject(val s: String)

//Java
public class JavaObject{
    private String s;

    JavaObject(String s){
        this.s=s;
    }

    public String getS(){
        return s;
    }

    public void setS(String s){
        this.s=s;
    }
    // copy
    // toString
    // hashCode 등등 생략
}

 


 

Java에 비해 Kotlin 문법이 훨씬 직관적이라는 것을 알 수 있다.