SlideShare a Scribd company logo
1 of 36
Download to read offline
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

What's hot

Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
Sunil Kumar Gunasekaran
 
The Logical Burrito - pattern matching, term rewriting and unification
The Logical Burrito - pattern matching, term rewriting and unificationThe Logical Burrito - pattern matching, term rewriting and unification
The Logical Burrito - pattern matching, term rewriting and unification
Norman Richards
 

What's hot (20)

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

Similar to Kotlin puzzler

Kotlin, 어떻게 동작하나요
Kotlin, 어떻게 동작하나요Kotlin, 어떻게 동작하나요
Kotlin, 어떻게 동작하나요
Chang W. Doh
 

Similar to Kotlin puzzler (20)

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

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Recently uploaded (20)

Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

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 * */