SlideShare a Scribd company logo
Kotlin Puzzler
Rainist

Park, MIREUK
Not a test
To understand Kotlin language
For fun(remember easily)
Not a test
To understand Kotlin language
For fun(remember easily)
Not a test
To understand Kotlin language
For fun(remember easily)
Engineer with Lover
data class Engineer(
val name: String,
val lover: Lover?
)
data class Lover(
val name: String,
val phoneNumber: String?
)
fun main(args: Array<String>) {
val james =
Engineer(
name = "James",
lover = Lover(
name = "Soo",
phoneNumber = null
)
)
james.lover?.let { girlFriend ->
girlFriend.phoneNumber?.let {
print("${girlFriend.name} phone number is $it")
}
} ?: run {
print("There is no lover.")
}
}
Engineer with Lover
data class Engineer(
val name: String,
val lover: Lover?
)
data class Lover(
val name: String,
val phoneNumber: String?
)
fun main(args: Array<String>) {
val james =
Engineer(
name = "James",
lover = Lover(
name = "Soo",
phoneNumber = null
)
)
james.lover?.let { girlFriend ->
girlFriend.phoneNumber?.let {
print("${girlFriend.name} phone number is $it")
}
} ?: run {
print("There is no lover.")
}
}
/**
* 1. "There is no lover."
* 2. "Soo phone number is null"
* 3. nothing
* */
Engineer with Lover
data class Engineer(
val name: String,
val lover: Lover?
)
data class Lover(
val name: String,
val phoneNumber: String?
)
fun main(args: Array<String>) {
val james =
Engineer(
name = "James",
lover = Lover(
name = "Soo",
phoneNumber = null
)
)
james.lover?.let { girlFriend ->
girlFriend.phoneNumber?.let {
print("${girlFriend.name} phone number is $it")
}
} ?: run {
print("There is no lover.")
}
}
/**
* 1. "There is no lover."
* 2. "Soo phone number is null"
* 3. nothing
* */
Engineer with Lover
data class Engineer(
val name: String,
val lover: Lover?
)
data class Lover(
val name: String,
val phoneNumber: String?
)
fun main(args: Array<String>) {
val james =
Engineer(
name = "James",
lover = Lover(
name = "Soo",
phoneNumber = null
)
)
james.lover?.let { girlFriend ->
girlFriend.phoneNumber?.let {
print("${girlFriend.name} phone number is $it")
}
} ?: run {
print("There is no lover.")
}
}
/**
* 1. "There is no lover."
* 2. "Soo phone number is null"
* 3. nothing
* */
let s check return, expression
data class Engineer(
val name: String,
val lover: Lover?
)
data class Lover(
val name: String,
val phoneNumber: String?
)
fun main(args: Array<String>) {
val james =
Engineer(
name = "James",
lover = Lover(
name = "Soo",
phoneNumber = null
)
)
james.lover?.let { girlFriend ->
girlFriend.phoneNumber?.let {
print("${girlFriend.name} phone number is $it")
}
} ?: run {
print("There is no lover.")
}
}
/**
* 1. "There is no lover."
* 2. "Soo phone number is null"
* 3. nothing
* */
Book, full of text
class Book {
var preface: Preface? = null
}
class Preface {
val text: String? = null
}
fun main(args: Array<String>) {
val book = Book()
val hasText: Boolean = book.preface?.text != null ?: false
print("hasText:$hasText")
}
Book, full of text
class Book {
var preface: Preface? = null
}
class Preface {
val text: String? = null
}
fun main(args: Array<String>) {
val book = Book()
val hasText: Boolean = book.preface?.text != null ?: false
print("hasText:$hasText")
}
/**
* 1. true
* 2. false
* */
Book, full of text
class Book {
var preface: Preface? = null
}
class Preface {
val text: String? = null
}
fun main(args: Array<String>) {
val book = Book()
val hasText: Boolean = book.preface?.text != null ?: false
print("hasText:$hasText")
}
/**
* 1. true
* 2. false
* */
Book, full of text
class Book {
var preface: Preface? = null
}
class Preface {
val text: String? = null
}
fun main(args: Array<String>) {
val book = Book()
val hasText: Boolean = book.preface?.text != null ?: false
print("hasText:$hasText")
}
/**
* 1. true
* 2. false
* */
Memo
import org.junit.Test
import org.junit.Assert.*
class MemoTest {
data class Memo(
val content: String? = null,
val photo: Photo? = null
)
data class Photo(
val imageUrl: String? = null
)
@Test
fun checkDefaultConstructor() {
val memo = Memo()
val content = memo.content ?: "empty"
val photoUrl = memo.photo?.run { imageUrl }
assert(content == "empty")
assert(photoUrl != null)
}
}
Memo
import org.junit.Test
import org.junit.Assert.*
class MemoTest {
data class Memo(
val content: String? = null,
val photo: Photo? = null
)
data class Photo(
val imageUrl: String? = null
)
@Test
fun checkDefaultConstructor() {
val memo = Memo()
val content = memo.content ?: "empty"
val photoUrl = memo.photo?.run { imageUrl }
assert(content == "empty")
assert(photoUrl != null)
}
}
/**
* 1. Success
* 2. Fail
* */
Memo
import org.junit.Test
import org.junit.Assert.*
class MemoTest {
data class Memo(
val content: String? = null,
val photo: Photo? = null
)
data class Photo(
val imageUrl: String? = null
)
@Test
fun checkDefaultConstructor() {
val memo = Memo()
val content = memo.content ?: "empty"
val photoUrl = memo.photo?.run { imageUrl }
assert(content == "empty")
assert(photoUrl != null)
}
}
/**
* 1. Success
* 2. Fail
* */
Memo
import org.junit.Test
import org.junit.Assert.*
class MemoTest {
data class Memo(
val content: String? = null,
val photo: Photo? = null
)
data class Photo(
val imageUrl: String? = null
)
@Test
fun checkDefaultConstructor() {
val memo = Memo()
val content = memo.content ?: "empty"
val photoUrl = memo.photo?.run { imageUrl }
assert(content == "empty")
assert(photoUrl != null)
}
}
/**
* 1. Success
* 2. Fail
* */
Memo
import org.junit.Test
import org.junit.Assert.*
class MemoTest {
data class Memo(
val content: String? = null,
val photo: Photo? = null
)
data class Photo(
val imageUrl: String? = null
)
@Test
fun checkDefaultConstructor() {
val memo = Memo()
val content = memo.content ?: "empty"
val photoUrl = memo.photo?.run { imageUrl }
assert(content == "empty")
assert(photoUrl != null)
}
}
/**
* 1. Success
* 2. Fail
* */
/**
* Throws an [AssertionError] calculated by [lazyMessage] if the [value] is false
* and runtime assertions have been enabled on the JVM using the *-ea* JVM option.
*/
@kotlin.internal.InlineOnly
public inline fun assert(value: Boolean, lazyMessage: () -> Any) {
if (_Assertions.ENABLED) {
if (!value) {
val message = lazyMessage()
throw AssertionError(message)
}
}
}
Writing failing test rst.
import org.junit.Test
import org.junit.Assert.*
class MemoTest {
data class Memo(
val content: String? = null,
val photo: Photo? = null
)
data class Photo(
val imageUrl: String? = null
)
@Test
fun checkDefaultConstructor() {
val memo = Memo()
val content = memo.content ?: "empty"
val photoUrl = memo.photo?.run { imageUrl }
assert(content == "empty")
assert(photoUrl != null)
}
}
/**
* 1. Success
* 2. Fail
* */
Null everywhere
private var account: String? = null
private var password: String? = null
fun main(args: Array<String>) {
val textBuilder = StringBuilder()
if (account?.toString() != null) {
textBuilder.append("account is $account.")
appendPassword(textBuilder)
} else {
textBuilder.append("account is empty.")
appendPassword(textBuilder)
}
print(textBuilder.toString())
}
private fun appendPassword(textBuilder: StringBuilder) {
if (password.toString() != null) {
textBuilder.append("password is $password.")
} else {
textBuilder.append("password is empty.")
}
}
Null everywhere
private var account: String? = null
private var password: String? = null
fun main(args: Array<String>) {
val textBuilder = StringBuilder()
if (account?.toString() != null) {
textBuilder.append("account is $account.")
appendPassword(textBuilder)
} else {
textBuilder.append("account is empty.")
appendPassword(textBuilder)
}
print(textBuilder.toString())
}
private fun appendPassword(textBuilder: StringBuilder) {
if (password.toString() != null) {
textBuilder.append("password is $password.")
} else {
textBuilder.append("password is empty.")
}
}
/**
* The root of the Kotlin class hierarchy. Every Kotlin class has [Any] as a superclass.
*/
public open class Any {
/**
* Returns a string representation of the object.
*/
public open fun toString(): String
}
/**
* Returns a string representation of the object. Can be called with a null receiver, in which case
* it returns the string "null".
*/
public fun Any?.toString(): String
Check before use.
private var account: String? = null
private var password: String? = null
fun main(args: Array<String>) {
val textBuilder = StringBuilder()
if (account?.toString() != null) {
textBuilder.append("account is $account.")
appendPassword(textBuilder)
} else {
textBuilder.append("account is empty.")
appendPassword(textBuilder)
}
print(textBuilder.toString())
}
private fun appendPassword(textBuilder: StringBuilder) {
if (password.toString() != null) {
textBuilder.append("password is $password.")
} else {
textBuilder.append("password is empty.")
}
}
My Data class
sealed class BankAccount {
abstract val id: String
abstract val name: String
override fun equals(other: Any?): Boolean {
return (other as? BankAccount)?.id == id
}
override fun hashCode(): Int {
return id.hashCode()
}
}
data class CheckingAccount(
override val id: String,
override val name: String,
val number: String
) : BankAccount()
fun main(args: Array<String>) {
val a = CheckingAccount(id = "001", name = "hello", number = "number")
val b = a.copy(number = "abc")
print("a and b is equal:${a == b}")
}
My Data class
sealed class BankAccount {
abstract val id: String
abstract val name: String
override fun equals(other: Any?): Boolean {
return (other as? BankAccount)?.id == id
}
override fun hashCode(): Int {
return id.hashCode()
}
}
data class CheckingAccount(
override val id: String,
override val name: String,
val number: String
) : BankAccount()
fun main(args: Array<String>) {
val a = CheckingAccount(id = "001", name = "hello", number = "number")
val b = a.copy(number = "abc")
print("a and b is equal:${a == b}")
}
/**
* 1. “a and b is equal:true”
* 2. “a and b is equal:false”
* */
My Data class
sealed class BankAccount {
abstract val id: String
abstract val name: String
override fun equals(other: Any?): Boolean {
return (other as? BankAccount)?.id == id
}
override fun hashCode(): Int {
return id.hashCode()
}
}
data class CheckingAccount(
override val id: String,
override val name: String,
val number: String
) : BankAccount()
fun main(args: Array<String>) {
val a = CheckingAccount(id = "001", name = "hello", number = "number")
val b = a.copy(number = "abc")
print("a and b is equal:${a == b}")
}
/**
* 1. “a and b is equal:true”
* 2. “a and b is equal:false”
* */
My Data class
sealed class BankAccount {
abstract val id: String
abstract val name: String
override fun equals(other: Any?): Boolean {
return (other as? BankAccount)?.id == id
}
override fun hashCode(): Int {
return id.hashCode()
}
}
data class CheckingAccount(
override val id: String,
override val name: String,
val number: String
) : BankAccount() {
override fun equals(other: Any?): Boolean {
return super.equals(other)
}
override fun hashCode(): Int {
return super.hashCode()
}
}
fun main(args: Array<String>) {
val a = CheckingAccount(id = "001", name = "hello", number = "number")
val b = a.copy(number = "abc")
print("a and b is equal:${a == b}")
}
My Data class
sealed class BankAccount {
abstract val id: String
abstract val name: String
final override fun equals(other: Any?): Boolean {
return (other as? BankAccount)?.id == id
}
final override fun hashCode(): Int {
return id.hashCode()
}
}
data class CheckingAccount(
override val id: String,
override val name: String,
val number: String
) : BankAccount()
fun main(args: Array<String>) {
val a = CheckingAccount(id = "001", name = "hello", number = "number")
val b = a.copy(number = "abc")
print("a and b is equal:${a == b}")
}
Double check doc.
sealed class BankAccount {
abstract val id: String
abstract val name: String
final override fun equals(other: Any?): Boolean {
return (other as? BankAccount)?.id == id
}
final override fun hashCode(): Int {
return id.hashCode()
}
}
data class CheckingAccount(
override val id: String,
override val name: String,
val number: String
) : BankAccount()
fun main(args: Array<String>) {
val a = CheckingAccount(id = "001", name = "hello", number = "number")
val b = a.copy(number = "abc")
print("a and b is equal:${a == b}")
}
My name is
class User {
lateinit var name: String
}
fun User.newInstance(name: String) = User().apply { this.name = name }
fun main(args: Array<String>) {
val james = User.newInstance("james")
print("Hello, my name is ${james.name}")
}
My name is
class User {
lateinit var name: String
}
fun User.newInstance(name: String) = User().apply { this.name = name }
fun main(args: Array<String>) {
val james = User.newInstance("james")
print("Hello, my name is ${james.name}")
}
My name is
class User {
lateinit var name: String
}
fun User.Companion.newInstance(name: String) = User().apply { … }
fun main(args: Array<String>) {
val james = User.newInstance("james")
print("Hello, my name is ${james.name}")
}
My name is
class User {
lateinit var name: String
companion object
}
fun User.Companion.newInstance(name: String) = User().apply { ... }
fun main(args: Array<String>) {
val james = User.newInstance("james")
print("Hello, my name is ${james.name}")
}
Gotta get that!
class Company {
val members =
mutableListOf(
"Mireuk",
"Sunghyun",
"ChaeYoon",
"BeomJoon"
)
val sizeValue: Int = getMemberCount()
val sizeGet: Int
get() = getMemberCount()
val sizeLazy by lazy { getMemberCount() }
private fun getMemberCount(): Int = members.size
}
fun main(args: Array<String>) {
Company().run {
println("1:$sizeValue, 2:$sizeGet, 3:$sizeLazy")
members.add("YOU")
println("4:$sizeValue, 5:$sizeGet, 6:$sizeLazy")
}
}
Gotta get that!
class Company {
val members =
mutableListOf(
"Mireuk",
"Sunghyun",
"ChaeYoon",
"BeomJoon"
)
val sizeValue: Int = getMemberCount()
val sizeGet: Int
get() = getMemberCount()
val sizeLazy by lazy { getMemberCount() }
private fun getMemberCount(): Int = members.size
}
fun main(args: Array<String>) {
Company().run {
println("1:$sizeValue, 2:$sizeGet, 3:$sizeLazy")
members.add("YOU")
println("4:$sizeValue, 5:$sizeGet, 6:$sizeLazy")
}
}
/**
* 1: 4, 2: 4, 3: 4
* 4: 4, 5: 5, 6: 4
* */
value is nal.
class Company {
val members =
mutableListOf(
"Mireuk",
"Sunghyun",
"ChaeYoon",
"BeomJoon"
)
val sizeValue: Int = getMemberCount()
val sizeGet: Int
get() = getMemberCount()
val sizeLazy by lazy { getMemberCount() }
private fun getMemberCount(): Int = members.size
}
fun main(args: Array<String>) {
Company().run {
println("1:$sizeValue, 2:$sizeGet, 3:$sizeLazy")
members.add("YOU")
println("4:$sizeValue, 5:$sizeGet, 6:$sizeLazy")
}
}
/**
* 1: 4, 2: 4, 3: 4
* 4: 4, 5: 5, 6: 4
* */
Kotlin puzzler

More Related Content

PDF
Swift, functional programming, and the future of Objective-C
PDF
Let the type system be your friend
ODP
Scala introduction
PDF
Async code on kotlin: rx java or/and coroutines - Kotlin Night Turin
PDF
Sneaking inside Kotlin features
PDF
From java to kotlin beyond alt+shift+cmd+k - Droidcon italy
PDF
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
Swift, functional programming, and the future of Objective-C
Let the type system be your friend
Scala introduction
Async code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Sneaking inside Kotlin features
From java to kotlin beyond alt+shift+cmd+k - Droidcon italy
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan

What's hot (19)

PPTX
Kotlin collections
ODP
From object oriented to functional domain modeling
KEY
Into Clojure
DOCX
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
PPTX
Benefits of Kotlin
PDF
Hey Kotlin, How it works?
PDF
Functions, Types, Programs and Effects
PDF
The Ring programming language version 1.3 book - Part 29 of 88
PDF
Pragmatic Real-World Scala (short version)
PDF
Dr Frankenfunctor and the Monadster
PDF
Implementing virtual machines in go & c 2018 redux
PDF
The Ring programming language version 1.10 book - Part 48 of 212
PPTX
Kotlin Collections
PDF
Pooya Khaloo Presentation on IWMC 2015
PDF
RxSwift 활용하기 - Let'Swift 2017
PDF
Scala in practice
PDF
Chaining and function composition with lodash / underscore
PDF
The Logical Burrito - pattern matching, term rewriting and unification
ODP
Kotlin collections
From object oriented to functional domain modeling
Into Clojure
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
Benefits of Kotlin
Hey Kotlin, How it works?
Functions, Types, Programs and Effects
The Ring programming language version 1.3 book - Part 29 of 88
Pragmatic Real-World Scala (short version)
Dr Frankenfunctor and the Monadster
Implementing virtual machines in go & c 2018 redux
The Ring programming language version 1.10 book - Part 48 of 212
Kotlin Collections
Pooya Khaloo Presentation on IWMC 2015
RxSwift 활용하기 - Let'Swift 2017
Scala in practice
Chaining and function composition with lodash / underscore
The Logical Burrito - pattern matching, term rewriting and unification
Ad

Similar to Kotlin puzzler (20)

PDF
First few months with Kotlin - Introduction through android examples
PDF
Kotlin Basics - Apalon Kotlin Sprint Part 2
PDF
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
PDF
Idiomatic Kotlin
PDF
Swift 함수 커링 사용하기
PPT
SDC - Einführung in Scala
PDF
Kotlin, 어떻게 동작하나요
PDF
かとうの Kotlin 講座 こってり版
PDF
Privet Kotlin (Windy City DevFest)
ODP
Introduction to Scala
PDF
Meetup di GDG Italia - Leonardo Pirro - Codemotion Rome 2018
ODP
Scala 2 + 2 > 4
PDF
A swift introduction to Swift
PDF
Kotlin Overview (PT-BR)
PDF
Kotlin Starter Pack
PDF
Introduction kot iin
PPTX
Android & Kotlin - The code awakens #03
PDF
Introduction to Scala
PDF
Idioms in swift 2016 05c
PDF
Persisting Data on SQLite using Room
First few months with Kotlin - Introduction through android examples
Kotlin Basics - Apalon Kotlin Sprint Part 2
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
Idiomatic Kotlin
Swift 함수 커링 사용하기
SDC - Einführung in Scala
Kotlin, 어떻게 동작하나요
かとうの Kotlin 講座 こってり版
Privet Kotlin (Windy City DevFest)
Introduction to Scala
Meetup di GDG Italia - Leonardo Pirro - Codemotion Rome 2018
Scala 2 + 2 > 4
A swift introduction to Swift
Kotlin Overview (PT-BR)
Kotlin Starter Pack
Introduction kot iin
Android & Kotlin - The code awakens #03
Introduction to Scala
Idioms in swift 2016 05c
Persisting Data on SQLite using Room
Ad

Recently uploaded (20)

PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Empathic Computing: Creating Shared Understanding
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Approach and Philosophy of On baking technology
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
A Presentation on Artificial Intelligence
PDF
Encapsulation theory and applications.pdf
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PPTX
Spectroscopy.pptx food analysis technology
PPT
Teaching material agriculture food technology
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
Machine Learning_overview_presentation.pptx
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Machine learning based COVID-19 study performance prediction
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Empathic Computing: Creating Shared Understanding
“AI and Expert System Decision Support & Business Intelligence Systems”
A comparative analysis of optical character recognition models for extracting...
Approach and Philosophy of On baking technology
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
A Presentation on Artificial Intelligence
Encapsulation theory and applications.pdf
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Spectroscopy.pptx food analysis technology
Teaching material agriculture food technology
MYSQL Presentation for SQL database connectivity
Machine Learning_overview_presentation.pptx
Building Integrated photovoltaic BIPV_UPV.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Diabetes mellitus diagnosis method based random forest with bat algorithm
Encapsulation_ Review paper, used for researhc scholars
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Programs and apps: productivity, graphics, security and other tools
Machine learning based COVID-19 study performance prediction

Kotlin puzzler

  • 2. Not a test To understand Kotlin language For fun(remember easily)
  • 3. Not a test To understand Kotlin language For fun(remember easily)
  • 4. Not a test To understand Kotlin language For fun(remember easily)
  • 5. Engineer with Lover data class Engineer( val name: String, val lover: Lover? ) data class Lover( val name: String, val phoneNumber: String? ) fun main(args: Array<String>) { val james = Engineer( name = "James", lover = Lover( name = "Soo", phoneNumber = null ) ) james.lover?.let { girlFriend -> girlFriend.phoneNumber?.let { print("${girlFriend.name} phone number is $it") } } ?: run { print("There is no lover.") } }
  • 6. Engineer with Lover data class Engineer( val name: String, val lover: Lover? ) data class Lover( val name: String, val phoneNumber: String? ) fun main(args: Array<String>) { val james = Engineer( name = "James", lover = Lover( name = "Soo", phoneNumber = null ) ) james.lover?.let { girlFriend -> girlFriend.phoneNumber?.let { print("${girlFriend.name} phone number is $it") } } ?: run { print("There is no lover.") } } /** * 1. "There is no lover." * 2. "Soo phone number is null" * 3. nothing * */
  • 7. Engineer with Lover data class Engineer( val name: String, val lover: Lover? ) data class Lover( val name: String, val phoneNumber: String? ) fun main(args: Array<String>) { val james = Engineer( name = "James", lover = Lover( name = "Soo", phoneNumber = null ) ) james.lover?.let { girlFriend -> girlFriend.phoneNumber?.let { print("${girlFriend.name} phone number is $it") } } ?: run { print("There is no lover.") } } /** * 1. "There is no lover." * 2. "Soo phone number is null" * 3. nothing * */
  • 8. Engineer with Lover data class Engineer( val name: String, val lover: Lover? ) data class Lover( val name: String, val phoneNumber: String? ) fun main(args: Array<String>) { val james = Engineer( name = "James", lover = Lover( name = "Soo", phoneNumber = null ) ) james.lover?.let { girlFriend -> girlFriend.phoneNumber?.let { print("${girlFriend.name} phone number is $it") } } ?: run { print("There is no lover.") } } /** * 1. "There is no lover." * 2. "Soo phone number is null" * 3. nothing * */
  • 9. let s check return, expression data class Engineer( val name: String, val lover: Lover? ) data class Lover( val name: String, val phoneNumber: String? ) fun main(args: Array<String>) { val james = Engineer( name = "James", lover = Lover( name = "Soo", phoneNumber = null ) ) james.lover?.let { girlFriend -> girlFriend.phoneNumber?.let { print("${girlFriend.name} phone number is $it") } } ?: run { print("There is no lover.") } } /** * 1. "There is no lover." * 2. "Soo phone number is null" * 3. nothing * */
  • 10. Book, full of text class Book { var preface: Preface? = null } class Preface { val text: String? = null } fun main(args: Array<String>) { val book = Book() val hasText: Boolean = book.preface?.text != null ?: false print("hasText:$hasText") }
  • 11. Book, full of text class Book { var preface: Preface? = null } class Preface { val text: String? = null } fun main(args: Array<String>) { val book = Book() val hasText: Boolean = book.preface?.text != null ?: false print("hasText:$hasText") } /** * 1. true * 2. false * */
  • 12. Book, full of text class Book { var preface: Preface? = null } class Preface { val text: String? = null } fun main(args: Array<String>) { val book = Book() val hasText: Boolean = book.preface?.text != null ?: false print("hasText:$hasText") } /** * 1. true * 2. false * */
  • 13. Book, full of text class Book { var preface: Preface? = null } class Preface { val text: String? = null } fun main(args: Array<String>) { val book = Book() val hasText: Boolean = book.preface?.text != null ?: false print("hasText:$hasText") } /** * 1. true * 2. false * */
  • 14. Memo import org.junit.Test import org.junit.Assert.* class MemoTest { data class Memo( val content: String? = null, val photo: Photo? = null ) data class Photo( val imageUrl: String? = null ) @Test fun checkDefaultConstructor() { val memo = Memo() val content = memo.content ?: "empty" val photoUrl = memo.photo?.run { imageUrl } assert(content == "empty") assert(photoUrl != null) } }
  • 15. Memo import org.junit.Test import org.junit.Assert.* class MemoTest { data class Memo( val content: String? = null, val photo: Photo? = null ) data class Photo( val imageUrl: String? = null ) @Test fun checkDefaultConstructor() { val memo = Memo() val content = memo.content ?: "empty" val photoUrl = memo.photo?.run { imageUrl } assert(content == "empty") assert(photoUrl != null) } } /** * 1. Success * 2. Fail * */
  • 16. Memo import org.junit.Test import org.junit.Assert.* class MemoTest { data class Memo( val content: String? = null, val photo: Photo? = null ) data class Photo( val imageUrl: String? = null ) @Test fun checkDefaultConstructor() { val memo = Memo() val content = memo.content ?: "empty" val photoUrl = memo.photo?.run { imageUrl } assert(content == "empty") assert(photoUrl != null) } } /** * 1. Success * 2. Fail * */
  • 17. Memo import org.junit.Test import org.junit.Assert.* class MemoTest { data class Memo( val content: String? = null, val photo: Photo? = null ) data class Photo( val imageUrl: String? = null ) @Test fun checkDefaultConstructor() { val memo = Memo() val content = memo.content ?: "empty" val photoUrl = memo.photo?.run { imageUrl } assert(content == "empty") assert(photoUrl != null) } } /** * 1. Success * 2. Fail * */
  • 18. Memo import org.junit.Test import org.junit.Assert.* class MemoTest { data class Memo( val content: String? = null, val photo: Photo? = null ) data class Photo( val imageUrl: String? = null ) @Test fun checkDefaultConstructor() { val memo = Memo() val content = memo.content ?: "empty" val photoUrl = memo.photo?.run { imageUrl } assert(content == "empty") assert(photoUrl != null) } } /** * 1. Success * 2. Fail * */ /** * Throws an [AssertionError] calculated by [lazyMessage] if the [value] is false * and runtime assertions have been enabled on the JVM using the *-ea* JVM option. */ @kotlin.internal.InlineOnly public inline fun assert(value: Boolean, lazyMessage: () -> Any) { if (_Assertions.ENABLED) { if (!value) { val message = lazyMessage() throw AssertionError(message) } } }
  • 19. Writing failing test rst. import org.junit.Test import org.junit.Assert.* class MemoTest { data class Memo( val content: String? = null, val photo: Photo? = null ) data class Photo( val imageUrl: String? = null ) @Test fun checkDefaultConstructor() { val memo = Memo() val content = memo.content ?: "empty" val photoUrl = memo.photo?.run { imageUrl } assert(content == "empty") assert(photoUrl != null) } } /** * 1. Success * 2. Fail * */
  • 20. Null everywhere private var account: String? = null private var password: String? = null fun main(args: Array<String>) { val textBuilder = StringBuilder() if (account?.toString() != null) { textBuilder.append("account is $account.") appendPassword(textBuilder) } else { textBuilder.append("account is empty.") appendPassword(textBuilder) } print(textBuilder.toString()) } private fun appendPassword(textBuilder: StringBuilder) { if (password.toString() != null) { textBuilder.append("password is $password.") } else { textBuilder.append("password is empty.") } }
  • 21. Null everywhere private var account: String? = null private var password: String? = null fun main(args: Array<String>) { val textBuilder = StringBuilder() if (account?.toString() != null) { textBuilder.append("account is $account.") appendPassword(textBuilder) } else { textBuilder.append("account is empty.") appendPassword(textBuilder) } print(textBuilder.toString()) } private fun appendPassword(textBuilder: StringBuilder) { if (password.toString() != null) { textBuilder.append("password is $password.") } else { textBuilder.append("password is empty.") } } /** * The root of the Kotlin class hierarchy. Every Kotlin class has [Any] as a superclass. */ public open class Any { /** * Returns a string representation of the object. */ public open fun toString(): String } /** * Returns a string representation of the object. Can be called with a null receiver, in which case * it returns the string "null". */ public fun Any?.toString(): String
  • 22. Check before use. private var account: String? = null private var password: String? = null fun main(args: Array<String>) { val textBuilder = StringBuilder() if (account?.toString() != null) { textBuilder.append("account is $account.") appendPassword(textBuilder) } else { textBuilder.append("account is empty.") appendPassword(textBuilder) } print(textBuilder.toString()) } private fun appendPassword(textBuilder: StringBuilder) { if (password.toString() != null) { textBuilder.append("password is $password.") } else { textBuilder.append("password is empty.") } }
  • 23. My Data class sealed class BankAccount { abstract val id: String abstract val name: String override fun equals(other: Any?): Boolean { return (other as? BankAccount)?.id == id } override fun hashCode(): Int { return id.hashCode() } } data class CheckingAccount( override val id: String, override val name: String, val number: String ) : BankAccount() fun main(args: Array<String>) { val a = CheckingAccount(id = "001", name = "hello", number = "number") val b = a.copy(number = "abc") print("a and b is equal:${a == b}") }
  • 24. My Data class sealed class BankAccount { abstract val id: String abstract val name: String override fun equals(other: Any?): Boolean { return (other as? BankAccount)?.id == id } override fun hashCode(): Int { return id.hashCode() } } data class CheckingAccount( override val id: String, override val name: String, val number: String ) : BankAccount() fun main(args: Array<String>) { val a = CheckingAccount(id = "001", name = "hello", number = "number") val b = a.copy(number = "abc") print("a and b is equal:${a == b}") } /** * 1. “a and b is equal:true” * 2. “a and b is equal:false” * */
  • 25. My Data class sealed class BankAccount { abstract val id: String abstract val name: String override fun equals(other: Any?): Boolean { return (other as? BankAccount)?.id == id } override fun hashCode(): Int { return id.hashCode() } } data class CheckingAccount( override val id: String, override val name: String, val number: String ) : BankAccount() fun main(args: Array<String>) { val a = CheckingAccount(id = "001", name = "hello", number = "number") val b = a.copy(number = "abc") print("a and b is equal:${a == b}") } /** * 1. “a and b is equal:true” * 2. “a and b is equal:false” * */
  • 26. My Data class sealed class BankAccount { abstract val id: String abstract val name: String override fun equals(other: Any?): Boolean { return (other as? BankAccount)?.id == id } override fun hashCode(): Int { return id.hashCode() } } data class CheckingAccount( override val id: String, override val name: String, val number: String ) : BankAccount() { override fun equals(other: Any?): Boolean { return super.equals(other) } override fun hashCode(): Int { return super.hashCode() } } fun main(args: Array<String>) { val a = CheckingAccount(id = "001", name = "hello", number = "number") val b = a.copy(number = "abc") print("a and b is equal:${a == b}") }
  • 27. My Data class sealed class BankAccount { abstract val id: String abstract val name: String final override fun equals(other: Any?): Boolean { return (other as? BankAccount)?.id == id } final override fun hashCode(): Int { return id.hashCode() } } data class CheckingAccount( override val id: String, override val name: String, val number: String ) : BankAccount() fun main(args: Array<String>) { val a = CheckingAccount(id = "001", name = "hello", number = "number") val b = a.copy(number = "abc") print("a and b is equal:${a == b}") }
  • 28. Double check doc. sealed class BankAccount { abstract val id: String abstract val name: String final override fun equals(other: Any?): Boolean { return (other as? BankAccount)?.id == id } final override fun hashCode(): Int { return id.hashCode() } } data class CheckingAccount( override val id: String, override val name: String, val number: String ) : BankAccount() fun main(args: Array<String>) { val a = CheckingAccount(id = "001", name = "hello", number = "number") val b = a.copy(number = "abc") print("a and b is equal:${a == b}") }
  • 29. My name is class User { lateinit var name: String } fun User.newInstance(name: String) = User().apply { this.name = name } fun main(args: Array<String>) { val james = User.newInstance("james") print("Hello, my name is ${james.name}") }
  • 30. My name is class User { lateinit var name: String } fun User.newInstance(name: String) = User().apply { this.name = name } fun main(args: Array<String>) { val james = User.newInstance("james") print("Hello, my name is ${james.name}") }
  • 31. My name is class User { lateinit var name: String } fun User.Companion.newInstance(name: String) = User().apply { … } fun main(args: Array<String>) { val james = User.newInstance("james") print("Hello, my name is ${james.name}") }
  • 32. My name is class User { lateinit var name: String companion object } fun User.Companion.newInstance(name: String) = User().apply { ... } fun main(args: Array<String>) { val james = User.newInstance("james") print("Hello, my name is ${james.name}") }
  • 33. Gotta get that! class Company { val members = mutableListOf( "Mireuk", "Sunghyun", "ChaeYoon", "BeomJoon" ) val sizeValue: Int = getMemberCount() val sizeGet: Int get() = getMemberCount() val sizeLazy by lazy { getMemberCount() } private fun getMemberCount(): Int = members.size } fun main(args: Array<String>) { Company().run { println("1:$sizeValue, 2:$sizeGet, 3:$sizeLazy") members.add("YOU") println("4:$sizeValue, 5:$sizeGet, 6:$sizeLazy") } }
  • 34. Gotta get that! class Company { val members = mutableListOf( "Mireuk", "Sunghyun", "ChaeYoon", "BeomJoon" ) val sizeValue: Int = getMemberCount() val sizeGet: Int get() = getMemberCount() val sizeLazy by lazy { getMemberCount() } private fun getMemberCount(): Int = members.size } fun main(args: Array<String>) { Company().run { println("1:$sizeValue, 2:$sizeGet, 3:$sizeLazy") members.add("YOU") println("4:$sizeValue, 5:$sizeGet, 6:$sizeLazy") } } /** * 1: 4, 2: 4, 3: 4 * 4: 4, 5: 5, 6: 4 * */
  • 35. value is nal. class Company { val members = mutableListOf( "Mireuk", "Sunghyun", "ChaeYoon", "BeomJoon" ) val sizeValue: Int = getMemberCount() val sizeGet: Int get() = getMemberCount() val sizeLazy by lazy { getMemberCount() } private fun getMemberCount(): Int = members.size } fun main(args: Array<String>) { Company().run { println("1:$sizeValue, 2:$sizeGet, 3:$sizeLazy") members.add("YOU") println("4:$sizeValue, 5:$sizeGet, 6:$sizeLazy") } } /** * 1: 4, 2: 4, 3: 4 * 4: 4, 5: 5, 6: 4 * */