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

Kotlin collections
Kotlin collectionsKotlin collections
Kotlin collectionsMyeongin Woo
 
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 modelingCodemotion
 
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
 
Hey Kotlin, How it works?
Hey Kotlin, How it works?Hey Kotlin, How it works?
Hey Kotlin, How it works?Chang W. Doh
 
Functions, Types, Programs and Effects
Functions, Types, Programs and EffectsFunctions, Types, Programs and Effects
Functions, Types, Programs and EffectsRaymond Roestenburg
 
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 88Mahmoud Samir Fayed
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Jonas Bonér
 
Dr Frankenfunctor and the Monadster
Dr Frankenfunctor and the MonadsterDr Frankenfunctor and the Monadster
Dr Frankenfunctor and the MonadsterScott Wlaschin
 
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 reduxEleanor McHugh
 
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 212Mahmoud Samir Fayed
 
Kotlin Collections
Kotlin CollectionsKotlin Collections
Kotlin CollectionsHalil Özcan
 
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 SlickHermann Hueck
 
RxSwift 활용하기 - Let'Swift 2017
RxSwift 활용하기 - Let'Swift 2017RxSwift 활용하기 - Let'Swift 2017
RxSwift 활용하기 - Let'Swift 2017Wanbok Choi
 
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 / underscoreNicolas Carlo
 
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 unificationNorman 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

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 examplesNebojša Vukšić
 
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 2Kirill Rozov
 
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 Waytdc-globalcode
 
Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlinintelliyole
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기진성 오
 
Kotlin, 어떻게 동작하나요
Kotlin, 어떻게 동작하나요Kotlin, 어떻게 동작하나요
Kotlin, 어떻게 동작하나요Chang W. Doh
 
かとうの Kotlin 講座 こってり版
かとうの Kotlin 講座 こってり版かとうの Kotlin 講座 こってり版
かとうの Kotlin 講座 こってり版Yutaka Kato
 
Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Cody Engel
 
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 Codemotion
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to SwiftGiordano Scalzo
 
Kotlin Overview (PT-BR)
Kotlin Overview (PT-BR)Kotlin Overview (PT-BR)
Kotlin Overview (PT-BR)ThomasHorta
 
Android & Kotlin - The code awakens #03
Android & Kotlin - The code awakens #03Android & Kotlin - The code awakens #03
Android & Kotlin - The code awakens #03Omar Miatello
 
Idioms in swift 2016 05c
Idioms in swift 2016 05cIdioms in swift 2016 05c
Idioms in swift 2016 05cKaz Yoshikawa
 
Persisting Data on SQLite using Room
Persisting Data on SQLite using RoomPersisting Data on SQLite using Room
Persisting Data on SQLite using RoomNelson Glauber Leal
 

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

CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
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 WorkerThousandEyes
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
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 FMESafe Software
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
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 WoodJuan lago vázquez
 

Recently uploaded (20)

CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
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
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
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
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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
 

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