Kotlin Type
- Java
- double 64 : 123.5
- float 32 : 123.5F / 123.5f
- long 64 : 123L
- int 32 : 123
- short 16
- byte 8
- String
-
final double variable = 123.5; final float variable = 123.5f; final int variable = 123; final short variable = 123; final byte variable = 123; final String variable = "a";
- Kotlin
- Double 64 : 123.5
- Float 35 : 123.5F / 123.5f
- Long 64 : 123
- Int 32 : 123
- Short 16
- Byte 8
- String
-
val variable: Double = 123.5 val variable: Float = 123.5f val variable: Int = 123 val variable: Short = 123 val variable: Byte = 123 val variable: String = "a" // 자동 타입 감지 val variable = 123.5 val variable = 123.5f val variable = 123 val variable = 123 val variable = 123 val variable = "a" // val variable = null 은 불가함 // 이 경우 Nothing/Void 사용 val variable: Nothing? = null Void variable = null;
Kotlin Variable
- Java
- (mutable) Read / Write 변수 선언
- String variable = "a";
- (inmutable) Read Only : final
- final String variable = "a";
- (mutable) Read / Write 변수 선언
- Kotlin
- (mutable) Read / Write : var
- var variable = "a"
- (inmutable) Read Only : val
- val variable = "a"
- (mutable) Read / Write : var
Kotlin variable syntax
- var <propertyName>[: <PropertyType>] [= <property_initializer>]
[<getter>]
[<setter>] - 괄호를 사용하는 부분은 모두 생략 가능
var name: String = ""
public final class KotlinSampleKt {
@NotNull
private static String name = "";
@NotNull
public static final String getName() {
return name;
}
pulbic static final void setName(@NotNull String var0) {
Intrinsics.checkParameterIsNotNull(var0, "<set-?>");
name = var0;
}
}
Kotlin variable syntax get/set custom
Class Sample<T> {
var list: list<T> = mutableListOf()
set(value) {
if (value.isNotEmpty()) {
field = value
}
}
get() = field
val isEmpty: Boolean
get() = this.list.isEmpty()
}
Kotlin variable Nullable
- Java
- 모든 변수가 null을 가질 수 있다.
- String variable = "a";
- variable = null;
- 모든 변수가 null을 가질 수 있다.
- Kotlin
- 모든 변수는 null을 허용하지 않는다.
- 허용하려면 물음표(?) 를 추가해야 한다.
- var variable = "a" / [ERROR:Null can not be a value of a non-null type String]
- variable = null / [ERROR:Null can not be a value of a non-null type String]
- var variable : String? = "a" / OK
Kotlin variable cast
- Java
- Object를 instance of 체크하여 형 변환
-
Object object = "name"; int index = 0; if(object instanceof Integer) { Index = (Int) object; } System.out.println("index " "+index)
-
- Object를 instance of 체크하여 형 변환
- Kotlin
- Kotlin에서는 as와 is를 제공
- as : 값의 casting
-
val a: Any? = "ABC" val b: Int? = a as? Int println("out b $b") // Out b null
-
- is : 값이 맞는지 체크
-
val a: Any? = "ABC" var b: Int? = 0 if (a is Int) { b = a as? Int } println("Out b $b") // Out b 0
-
Kotlin variable cast Notnull
- Kotlin
- as : 값의 casting 할 경우 null return
- Null이 나오지 않게 하려면?
- -> 깔끔하지 못하고, 값이 변경될 가능성이 있음
// Null이 나오지 않게 하도록 val a: Any? = "ABC" val b: Int? = a as? Int if (b == null) { b = 0 } println("out b $b") // Out b 0
- Elvis Operator
-
val a: Any? = "ABC" val b: Int? = a as? Int ?: 0 println("out b $b") // Out b 0
- as : 값의 casting 할 경우 null return
Kotlin variable Elvis Opertator
- Kotlin
- 코틀린에선 삼항식을 쓰지 않고, Elvis Operator를 이용하여 삼항식처럼 사용
- 기존 문장
- val l: Int = if (b != null) b.length else -1
- ?: (else)
- val l = b?.length ?: -1
- Other Example
-
fun foo(node: Node) String? { val parent = node.getParent() ?: return null val name = node.getName() ?: throw IllegalArgumentException("name expected") // ... }
-
- 정말 null이 필요한 경우
- val l = b!!.length
- NullpointException 발생
Kotlin variable cast
- Java
- Object를 instance of 체크하여 형 변환
-
Object object = "name"; int index = 0; if(object instanceof Integer) { Index = (Int) object; } System.out.println("index " "+index)
-
- Object를 instance of 체크하여 형 변환
- Kotlin
- is와 when을 활용 시 if문을 줄일 수 있다.
-
val a: Any? = "ABC" when (a) { is Int -> println(a) is String -> println(a) else -> println(:nothing") } // print "ABC"
-
- is와 when을 활용 시 if문을 줄일 수 있다.
Kotlin Class
- Java
- 기본 틀
-
public class JavaSample { }
-
- 생성자1 추가
-
public class JavaSample { public JavaSample() { } }
-
- 변수 받아오기 - 생성자 1
-
public class JavaSample { private final String a; public JavaSample(String a) { this.a = a; } }
-
- 생성자2 추가
-
public class JavaSample { private final String a; public JavaSample(String a) { this.a = a; } public JavaSample(String a, String b) { this(a); this.b = b; } }
-
- 함수 추가
-
public class JavaSample { private final String a; public JavaSample(String a) { this.a = a; } public JavaSample(String a, String b) { this(a); this.b = b; } public void print() { System.out.Println("Out "+a+", "+b); } }
-
- 기본 틀
- Kotlin
- 기본 틀 / Default 접근 제어자 없음 (전역)
-
class KotlinSample { }
-
- 생성자1 추가
-
class KotlinSample constructor(){ }
-
- 변수 받아오기 - 생성자1
-
class KotlinSample constructor(val a: String){ }
-
- 생성자2 추가
-
class KotlinSample constructor(val a: String) { constructor(a: String, b:String) : this(a) }
-
- 함수 추가
-
class KotlinSample constructor(val a: String) { constructor(a: String, b:String) : this(a) fun print() { println("Out $a, $b") // (ERROR: Unresolbed reference: b) } }
-
- 1개의 primary constructor
-
class KotlinSample constructor(val a: String)
-
- N개의 secondary constructor
- primary constructor를 호출하지 않으면 오류 발생
-
class KotlinSample constructor(val a: String) { constructor(a: String, b: String) : this(a) constructor(a: String, b: String, c:String) : this(a,b) }
-
- primary constructor를 호출하지 않으면 오류 발생
- 기본 틀 / Default 접근 제어자 없음 (전역)
Kotlin class primary constructor
- Kotlin
- 변수를 선언과 동시에 전역 변수로 가진다 (var/val)
-
class KotlinSample constructor(val a: String)
- decomplie 하여 확인 가능
-
public final class KotlinSample { @NotNull private final String a; @NotNull public final String getA() { return this.a; } public KotlinSample(@NotNull String a) { Intrinsics.checkParameterIsNotNull(a, "a"); super(); this.a = a; } }
-
-
- 전역변수를 정의할 수 없다 (var/val)
-
class KotlinSample constructor(val a: String) { constructor(a: String, b: String) : this(a) //ERROR: 'val/var' on secondary constructor parameter is not allowed }
- 사용하려면?
-
class KotlinSample constructor(val a: String) { private var b: String = "" constructor(a: String, b: String) : this(a) { this.b = b } }
-
-
- 변수를 선언과 동시에 전역 변수로 가진다 (var/val)
Kotlin class init {}
- 자바의 경우 생성자로부터 받아온 변수를 해당 클래스에서 사용할 때
생성자 내에서 [this.클래스변수 = 매개변수] 같은 형식으로 받아올 수 있다. - 코틀린은 생성자 영역이 없어서 이렇게 할 수가 없다.
즉 [this.클래스변수*= 매개변수]를 쓸 수가 없는 것이다
* 코틀린 내에서 생성자로부터 받아온 변수를 해당 클래스에서 사용할 수 있는 방법
- init 블록 내에서 초기화하여 사용한다.
- 생성자 인자 == 클래스 변수이기 때문에 init 영역의 초기화가 없어도 외부에서 받아온 값을 그대로 쓸 수 있다.
- init block은 primary constructor를 위한 도구
- 모든 secondary constructor는 primary constructor를 호출해야 한다.
-
class KotlinSample constructor(val a:String) { Private var b: String = "" init { println("out A : %a, out B : $b") } constructor(a: String, b: String) : this(a) { this.b = b println("out A : %a, out B : $b") } } //out A: a, out B : //B는 출력하지 않는다. //out A: a, out B : b
-
- 생성자 인자 / Primary constructor에게 몰아주자
-
Class KotlinSample constructor(val a: String, val b: String) { init { println("out A : $a, out B : $b") } constructor(a: String) : this(a,"") }
-
- 생성자 인자 / Primary 생성자의 Default 변수 지정 가능
-
class Smaple constructor(val name: String, val name2: String = "", val age: Int) { init { println("name $name name2 $name2 age $age") } private fun aaa() { println("name $name name2 $name2 age $age") } } class UnitTest { @Test fun test() { Sample("a","b",0) // 가능 Sample(name = "a", age = 0) // 가능 } }
-
Kotlin Class 정리
- 1개의 primary constructor
- N개의 secondary constructor
- secondary constructor에서는 primary constructor를 호출해야 한다.
- primary constructor를 위한 init block를 제공한다.
- primary constructor와 함께 오는 변수는 전역변수이다.
- default 값을 가질 수 있다.
- default value 정의한 생성자를 Java에서 부르려면, @JvmOverload를 적용해야 한다.
'Back-end > Kotlin' 카테고리의 다른 글
Java to Kotlin 변환 실습 I (0) | 2021.12.14 |
---|---|
코틀린(Kotlin) 기본 문법 II (상속 / 인터페이스 / 데이터 클래스 / 싱글톤 / 람다) (0) | 2021.12.07 |