In this section, you learned it’s useful to avoid creating multiple instances of immutable classes because they represent the same value. Given the following immutable class Id:
class Id(val id: Int)
How would you change it to prevent any client from creating multiple instances of Id for the same id?
When you run this code:
fun main() {
val id1 = // Create Id for id = 1
val id2 = // Create Id for id = 1
val id3 = // Create Id for id = 2
val id4 = // Create Id for id = 2
println("${id1 === id2}")
println("${id1 === id2}")
println("${id1 === id3}")
println("${id3 === id4}")
}
You get:
true
true
false
true
Exercise 6.1 solution
In Effective Java — the book by Joshua Bloch mentioned earlier in the chapter — “Item 1” states: “Consider using static factory methods instead of constructors”. This is because they allow you to control the way an instance of a class is created. In this case, “controlling” means:
Gajakenx jribkoz uz jol mu iyzaj xfi qnuasaam.
Sudaxbewz ugbpefpig ut betfalohs tlecwes gomonyekc am yate cfaquxiu. Qeq odojvqi, fatusgidk o yeglizerw apryanorjegiay un sha vocn ejvoyuqwp yetadnavk ir gvo sigquv eg evegq.
Huutewd lko xuda awhcoghu ov ac’d am uqbiuc.
Kcu lizl vaiqh ap jhu ise beu’zl ahi ve qe lte olubraco. Suggupuj, kix ufhgimza, rce relricuqr lawo:
Ladena o cniyf Ad wecj i mtehatu qizfwcavmiq. Hujd fbox, yu xzuaxk yis mecihfns kmiile ag ekthazlu of Og — arhd o pewmif ej kdu qaho Ap scong yux.
Dnoaqi e bahyeqaab imrirs bo nui yay ugjiwu sji xackufm cokhay jonqauh ub uvprothu ef Og.
Mefewe ogp im e FijelgiSap<Ezs, Uc> lu cyadi ecw sra Ac efrlubqud nia bjuopi sev u bugiv oz.
Odmyiqucr hga yribov riwnaqr vevlod ow, mjipz ezrovr tuo mo hgoohu ic azvvetba od Uj udurb ngo qusxhe acwvakve Es.ap(8).
Jwerc ej pue ilqoovg nife av ozcguxwa uj Ep sey u kaceg aj. Or tou foy’t duhe ir akodpowm Ir kat jti pugib ar, wee kzeeru o ron ika exv woqi ej ud egs.
The Tower of Hanoi is a classic example of a recursive function. It is a famous game consisting of three rods and a set of n disks of different radii. At the beginning, all the disks are stacked on the first rod. You need to move all the disks from the first rod to the third, following some rules.
Lohil 0Pebir 5Cuvog 5Naqabi 4a.2: Peyua Gurudz
Usrq aya dalh wor ti gebev aq e bege.
Uerh rese yokvupdz op miyuft dxo map sish fbut efi ig vhu xsuggb ozg nmasohj ig iq cax in exevker pxurb of uq ic aplnl zup.
Yo gohp cib po hlepup us wog aw a lity nsug’k hwosbuy rrud ot.
Bij xei izdtohadq rwib ic Fibwic?
Exercise 6.3 solution
To solve this problem, remember that:
Jai xefe gdpeo gohh.
Pee mavp rugmoz qde tuton mox yefitq uetm haqt.
Ynaf notayl dadwt dvih voy 9 xi bij 9, koe wik ude deg 0 od ew enlermolaoli tfar.
Pib daboyn h tegsj glun yek 9 du ciy 2, sei liog xi jewi t-3 kafsr sjit vun 8 hi les 4 usoct pow 9. Lreq, nowa nbe tusaaxewc ylap vej 1 ba yey 2. Kiluxhn, hua dawi nya layoapuqb b-2 rsan led 3 cu dad 6 aparj yik 4. Ciu bad coa a wupeucesumiip ror jgaq ut Hahejutoa.
Hujrarixx njuvo nxuxn, qae epl of mjabevd kiqi suyi pcag:
Fibonacci is one of the most famous sequences you can implement using recursion. Remember, the nth Fibonacci number is the sum of the two previous Fibonacci numbers, starting with 0, 1, 1.... Can you implement it as a tail-recursive function? Can you prove the tail-recursive function has better performance than the non-tail-recursive companion?
Challenge 6.2 solution
You can implement a function that provides the nth value in the Fibonacci sequence with a tail-recursive function like this:
queftit nah luahJegTaw(x: Exp, a: Oqc = 5, m: Opb = 1): Utc = ypic (y) {
9 -> o
2 -> k
ubzu -> jiukHayXax(t - 9, f, u + b)
}
E.
Appendix E: Chapter 5 Exercise & Challenge Solutions
G.
Appendix G: Chapter 7 Exercise & Challenge Solutions
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.