Last active
August 1, 2017 09:04
-
-
Save arawn/2354024e2ee534c1641da04e8142b3fd to your computer and use it in GitHub Desktop.
Introduction to Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlin.system.measureNanoTime | |
import kotlin.system.measureTimeMillis | |
/* | |
* 코틀린 클래스는 프로퍼티를 가질 수 있다. | |
*/ | |
object Properties { | |
class Person1 { | |
var id: Int = 0 | |
var name: String = "" | |
} | |
// var : mutable | |
// val : immuatable | |
class Person2(val id: Int, var name: String) | |
init { | |
// new 키워드는 사용 안함 | |
val javaPerson1 = Example.Person1() | |
javaPerson1.id = 1 | |
javaPerson1.name = "yongkwon.park" | |
val person1 = Person1() | |
person1.id = 1 | |
person1.name = "yongkwon.park" | |
val person2 = Person2(2, "yunseok.choi") | |
println("person1 is $person1") | |
println("person2 is $person2") | |
} | |
} | |
object DataClass { | |
// 뉴트리션 팩트, 식품영양정보 | |
// Create a POJO with | |
// getters, setters, equals(), hashCode(), toString() and copy() | |
data class NutritionFacts(val foodName: String, | |
val calories: Int, | |
val protein: Int, | |
val carbohydrates: Int, | |
val fat: Int, | |
val description: String) | |
init { | |
val rice = NutritionFacts("Rice",312,0,23,0,"Tasty, nutritious grains") | |
val brownRice = rice.copy(foodName = "Brown Rice", calories = 116) | |
println("rice is: $rice") | |
println("brownRice is: ${brownRice.foodName}, ${brownRice.description}") | |
} | |
} | |
object DefaultAndNamedArguments { | |
data class NutritionFacts(val foodName: String, | |
val calories: Int, | |
val protein: Int = 0, | |
val carbohydrates: Int = 0, | |
val fat: Int = 0, | |
val description: String = "") { | |
} | |
// Default | |
val pizza = NutritionFacts("Pizza", 442, 12, 27, 24, "Developer's best friend") | |
val pasta = NutritionFacts("Pasta", 371, 14, 25, 11) | |
val noodleSoup = NutritionFacts("Noodle Soup", 210) | |
// Named | |
val burger = NutritionFacts("Hamburger", calories = 541, fat = 33, protein = 14) | |
val rice = NutritionFacts("Rice", 312, carbohydrates = 23, description = "Tasty, nutritious grains") | |
init { | |
javaClass.methods.forEach { | |
if(it.name.startsWith("get") && it.name != "getClass") println(it.invoke(this)) | |
} | |
} | |
} | |
object Objects { | |
// 싱글톤 클래스 작성 | |
object Global { | |
// 타입 추론 | |
val PI = 3.14 | |
val longValue = 10L | |
} | |
init { | |
println(Global) | |
println(Global) | |
println("pi is ${Global.PI}") | |
println("longValue type is ${Global.longValue.javaClass}") | |
} | |
} | |
object NullSafety { | |
// 변수 또는 프로퍼티 선언시 Non-Null 타입이 기본, Non-Null 타입에 null 할당시 컴파일 오류 | |
// val nonNull: String = null | |
// Nullable 타입은 ? 키워드를 사용해서 선언, null 할당 가능 | |
val nullable: String? = null | |
init { | |
println("NullSafety") | |
// 검증 없이 Nullable 타입 사용시 컴파일 오류 | |
// println(nullable.length) | |
// if 연산자로 검증하거나 | |
if (nullable != null) { | |
println(nullable.length) | |
} | |
// 안전한 호출 ?. 연산사를 사용 | |
println(nullable?.length) | |
println("") | |
} | |
} | |
// Flow-sensitive typing | |
object SmartCasts { | |
open class Person | |
class Employee(val vacationDays: Int) : Person() | |
fun validateVacations(person: Person) : Boolean { | |
return if (person is Employee) { | |
person.vacationDays < 15 | |
} else { | |
false | |
} | |
} | |
init { | |
if (validateVacations(Employee(5))) { | |
println("You need to take some more time off!!!") | |
} | |
} | |
} | |
// 고차 함수는 파라미터로 함수를 받거나 함수를 리턴하는 함수이다. | |
// 고차 함수에 넘길 함수를 람다식으로 작성 할 수 있다. | |
object HigherOrderFunctionsAndLambdas { | |
init { | |
val doubled = listOf(2, 4, 6).map { it * 2 } | |
val cities = listOf("New York", "Los Angeles", "Chicago", "Houston", "Phoenix", "Philadelphia") | |
val filtered = cities.filter { it.length > 7 } | |
.sortedBy { it } | |
.map { it.toUpperCase() } | |
} | |
} | |
object ExtensionFunctions { | |
fun String.isNumeric(): Boolean { | |
return this.matches("\\d+".toRegex()) | |
} | |
class User(var email: String = "", var password: String = "", var active: Boolean = false) | |
class Employee(val vacationDays: Int) | |
init { | |
println("NaN is numeric: " + "NaN".isNumeric()) | |
println("20170802 is numeric: " + "20170802".isNumeric()) | |
val data: String? = null | |
if (data != null) { | |
// data 사용 | |
} | |
data?.let { | |
// it 은 data, 블럭의 마지막 값을 반환 | |
it.length | |
} | |
var user1 = User() | |
user1.email = "user@woowahah.com" | |
user1.password = "password" | |
user1.active = true | |
var user2 = User().apply { | |
// 생성된 user 객체를 람다식에 리시버로 전달, 람다식 내부에 스코프는 user 로 변경 | |
// user 객체를 반환 (Builder 패턴 형태로 사용 가능) | |
email = "user@woowahah.com" | |
password = "password" | |
active = true | |
} | |
val employee = Employee(20) | |
employee.takeIf { it.vacationDays < 15 } | |
.run { println("not implemented") } | |
println("") | |
} | |
} | |
object StandardLibrary { | |
init { | |
val elapsedNanoTime = measureNanoTime { | |
// 시간을 측정할 로직 | |
} | |
val elapsedTimeMillis = measureTimeMillis { | |
// 시간을 측정할 로직 | |
} | |
} | |
} | |
fun main(args: Array<String>) { | |
Properties | |
DataClass | |
DefaultAndNamedArguments | |
Objects | |
NullSafety | |
SmartCasts | |
HigherOrderFunctionsAndLambdas | |
ExtensionFunctions | |
StandardLibrary | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment