├── 100
├── src_chapt10_sect001_What_NULL_is.txt
└── src_chapt10_sect002_How_Nullability_Gets_Handled_Inside_Kotlin.txt
├── 110
├── src_chapt11_sect001_Identity_in_Kotlin.txt
└── src_chapt11_sect003_Equals_and_Hash_Code.txt
├── 120
├── src_chapt12_sect001_Kotlin_And_Functional_Programming.txt
├── src_chapt12_sect002_Functions_Without_Names__Lambda_Functions.txt
├── src_chapt12_sect003_Loops_Once_Again.txt
├── src_chapt12_sect004_Functions_With_Receivers.txt
├── src_chapt12_sect005_Inline_Functions.txt
└── src_chapt12_sect006_Filters.txt
├── 130
├── src_chapt13_sect000_.txt
├── src_chapt13_sect001_Simple_Generics.txt
├── src_chapt13_sect002_Declaration_Side_Variance.txt
├── src_chapt13_sect003_Variance_For_Immutable_Collections.txt
├── src_chapt13_sect004_Type_Projections.txt
├── src_chapt13_sect005_Star_Projections.txt
├── src_chapt13_sect006_Generic_Functions.txt
└── src_chapt13_sect007_Generic_Constraints.txt
├── 140
├── src_chapt14_sect000_.txt
├── src_chapt14_sect001_Annotations_in_Kotlin.txt
├── src_chapt14_sect002_Annotation_Characteristics.txt
├── src_chapt14_sect003_Applying_Annotations.txt
├── src_chapt14_sect004_Annotations_With_Array_Parameter.txt
├── src_chapt14_sect005_Reading_Annotations.txt
└── src_chapt14_sect007_Custom_Annotations.txt
├── 160
├── src_chapt16_sect002_Classes.txt
├── src_chapt16_sect003_Generator_Functions.txt
├── src_chapt16_sect014_Joining.txt
├── src_chapt16_sect016_Zipping.txt
└── src_chapt16_sect018_Sequences.txt
├── 170
├── src_chapt17_sect001_The_Math_API.txt
├── src_chapt17_sect002_The_Date_Time_API__API_Level_25_or_Less.txt
├── src_chapt17_sect003_The_Date_Time_API__API_Level_26_or_Greater.txt
├── src_chapt17_sect004_Input_And_Output.txt
├── src_chapt17_sect005_Using_Reflection.txt
└── src_chapt17_sect006_Regular_Expressions.txt
├── 180
├── src_chapt18_sect001_Basic_Multithreading_The_Java_Way.txt
├── src_chapt18_sect002_Advanced_Multithreading_The_Java_Way.txt
└── src_chapt18_sect003_Kotlin_Coroutines.txt
├── 190
├── src_chapt19_sect001_Adding_External_Libraries.txt
├── src_chapt19_sect004_External_Libraries_And_Nullability.txt
└── src_chapt19_sect005_Creating_Your_Own_Library.txt
├── 200
├── src_chapt20_sect001_XML_Processing.txt
└── src_chapt20_sect002_JSON_Processing.txt
├── 900
└── src_chapt90_sect001_Solutions_to_The_Exercises.txt
├── .gitattributes
├── 000
└── src_chapt00_sect000_.txt
├── 010
├── src_chapt01_sect005_Continuing_with_The_HelloKotlin_App.txt
└── src_chapt01_sect006_Using_The_Command_Line.txt
├── 020
├── src_chapt02_sect001_Kotlin_And_Object_Oriented_Programming.txt
├── src_chapt02_sect002_A_Simple_Number_Guessing_Game.txt
├── src_chapt02_sect003_Constructors.txt
├── src_chapt02_sect004_If_Classes_Are_Not_Needed__Singleton_Objects.txt
├── src_chapt02_sect005_If_State_Doesn_t_Matter__Companion_Objects.txt
├── src_chapt02_sect006_Describing_a_Contract__Interfaces.txt
└── src_chapt02_sect007_Structuring_And_Packages.txt
├── 030
├── src_chapt03_sect001_Properties_And_Their_Types.txt
├── src_chapt03_sect002_Member_Functions.txt
├── src_chapt03_sect003_Inheritance.txt
├── src_chapt03_sect004_Local_Variables.txt
├── src_chapt03_sect005_Visibility_of_Classes_And_Class_Members.txt
├── src_chapt03_sect006_Self_Reference__This.txt
└── src_chapt03_sect007_Converting_Classes_to_Strings.txt
├── 040
├── src_chapt04_sect001_Anonymous_Classes.txt
├── src_chapt04_sect002_Inner_Classes.txt
├── src_chapt04_sect004_Importing_Functions_And_Properties.txt
├── src_chapt04_sect005_Data_Classes.txt
├── src_chapt04_sect006_Enumerations.txt
├── src_chapt04_sect007_Custom_Property_Accessors.txt
├── src_chapt04_sect008_Kotlin_Extensions.txt
├── src_chapt04_sect009_Functions_With_Tail_Recursion.txt
├── src_chapt04_sect010_Infix_Operators.txt
├── src_chapt04_sect011_Operator_Overloading.txt
└── src_chapt04_sect012_Delegation.txt
├── 050
├── src_chapt05_sect001_Expressions_Examples.txt
├── src_chapt05_sect002_Expressions_Ubiquity.txt
├── src_chapt05_sect003_Numerical_Expressions.txt
├── src_chapt05_sect004_Boolean_Expressions.txt
├── src_chapt05_sect007_Other_Operators.txt
└── src_chapt05_sect008_Conversions.txt
├── 060
├── src_chapt06_sect003_Class_Comments.txt
└── src_chapt06_sect004_Function_And_Property_Comments.txt
├── 070
├── src_chapt07_sect001_Ifs_And_Whens.txt
├── src_chapt07_sect002_Ranges.txt
├── src_chapt07_sect003_For_And_While_Loops.txt
├── src_chapt07_sect004_Scoping_Functions.txt
└── src_chapt07_sect005_Conditional_Execution.txt
├── 080
├── src_chapt08_sect001_Kotlin_And_Exceptions.txt
├── src_chapt08_sect002_More_Exceptions_Types.txt
├── src_chapt08_sect003_Throwing_Exceptions_Yourself.txt
└── src_chapt08_sect004_Exceptions_in_Expressions.txt
├── 090
├── src_chapt09_sect001_Defining_And_Using_Arrays.txt
├── src_chapt09_sect002_Array_Instantiation.txt
├── src_chapt09_sect004_Sets__Lists_And_Maps.txt
├── src_chapt09_sect005_Pairs_and_Triples.txt
├── src_chapt09_sect006_Loops_Over_Data_Containers.txt
├── src_chapt09_sect008_Grouping__Folding__Reducing_And_Zipping.txt
├── src_chapt09_sect010_The_Spread_Operator.txt
└── src_chapt09_sect012_A_Statistics_Class_For_The_NumberGuess_App.txt
├── 9781484244661.jpg
├── Contributing.md
├── LICENSE.txt
├── README.md
└── errata.md
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 |
--------------------------------------------------------------------------------
/000/src_chapt00_sect000_.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 00:
3 | //// Frontmatter
4 | //// Section: 0.
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | arrayOf("Blue", "Green", "Yellow", "Gray").
10 | filter { it.startsWith("G") }.
11 | forEach { item ->
12 | println(item)
13 | }
14 |
15 | //----#### SNIPPET #### - 2
16 | https://github.com/Apress/learn-kotlin-for-android-development
17 |
--------------------------------------------------------------------------------
/010/src_chapt01_sect005_Continuing_with_The_HelloKotlin_App.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 01:
3 | //// Your First Kotlin Application: Hello Kotlin
4 | //// Section: 5. Continuing with The HelloKotlin App
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 |
10 |
20 |
21 |
29 |
33 |
41 |
42 |
43 |
44 | //----#### SNIPPET #### - 2
45 | package kotlin.hello.hellokotlin
46 |
47 | import android.support.v7.app.AppCompatActivity
48 | import android.os.Bundle
49 | import android.view.View
50 | import kotlinx.android.synthetic.main.activity_main.*
51 | import java.util.*
52 |
53 | class MainActivity : AppCompatActivity() {
54 |
55 | override fun onCreate(savedInstanceState: Bundle?) {
56 | super.onCreate(savedInstanceState)
57 | setContentView(R.layout.activity_main)
58 | }
59 |
60 | fun go(v:View) {
61 | text.setText("Hello Kotlin!" + "\n" + Date())
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/010/src_chapt01_sect006_Using_The_Command_Line.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 01:
3 | //// Your First Kotlin Application: Hello Kotlin
4 | //// Section: 6. Using The Command Line
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | cd [PATH] #for Linux and Mac OS X and Windows
10 |
11 | //----#### SNIPPET #### - 2
12 | ./gradlew app:build #for Linux and Mac OS X
13 | gradlew app:build #for Windows
14 |
15 | //----#### SNIPPET #### - 3
16 | ./gradlew -help #for Linux and Mac OS X
17 | ./gradlew tasks #for Linux and Mac OS X
18 | gradlew -help #for Windows
19 | gradlew tasks #for Windows
20 |
--------------------------------------------------------------------------------
/020/src_chapt02_sect001_Kotlin_And_Object_Oriented_Programming.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 02:
3 | //// Classes And Objects: Object Orientation Philosophy
4 | //// Section: 1. Kotlin And Object Oriented Programming
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | class ClassName(Parameter-Declaration1,
10 | Parameter-Declaration2, ...) {
11 | [Class-Body]
12 | }
13 |
14 | //----#### SNIPPET #### - 2
15 | val Variable-Name:Variable-Type = value
16 |
17 | //----#### SNIPPET #### - 3
18 | var Variable-Name:Variable-Type = value
19 |
20 | //----#### SNIPPET #### - 4
21 | class ClassName(Parameter-Declaration1,
22 | Parameter-Declaration2, ...) {
23 | ...
24 | val propertyName:PropertyType = [init-value]
25 | var propertyName:PropertyType = [init-value]
26 | ...
27 | }
28 |
29 | //----#### SNIPPET #### - 5
30 | class ClassName(Parameter-Declaration1,
31 | Parameter-Declaration2, ...) {
32 | ...
33 | init {
34 | // initialization actions...
35 | }
36 | }
37 |
38 | //----#### SNIPPET #### - 6
39 | class ClassName(Parameter-Declaration1,
40 | Parameter-Declaration2, ...) {
41 | val someProperty:PropertyType
42 | ...
43 | init {
44 | someProperty = [some value]
45 | // more initialization actions...
46 | }
47 | }
48 |
49 | //----#### SNIPPET #### - 7
50 | class ClassName {
51 | var someProperty:PropertyType = [init-value]
52 | ...
53 | init {
54 | ...
55 | someProperty = [some new value]
56 | ...
57 | }
58 | }
59 |
60 | //----#### SNIPPET #### - 8
61 | class Invoice(val buyerFirstName:String,
62 | val buyerLastName:String,
63 | val date:String,
64 | val goodName:String,
65 | val amount:Int,
66 | val pricePerItem:Double) {
67 | }
68 |
69 | //----#### SNIPPET #### - 9
70 | class Invoice(val buyerFirstName:String,
71 | val buyerLastName:String,
72 | val date:String,
73 | val goodName:String,
74 | val amount:Int,
75 | val pricePerItem:Double)
76 | {
77 | val buyerFullName:String
78 | val totalPrice:Double
79 | }
80 |
81 | //----#### SNIPPET #### - 10
82 | class Invoice(val buyerFirstName:String,
83 | val buyerLastName:String,
84 | val date:String,
85 | val goodName:String,
86 | val amount:Int,
87 | val pricePerItem:Double)
88 | {
89 | val buyerFullName:String
90 | val totalPrice:Double
91 | init {
92 | buyerFullName = buyerFirstName + " " +
93 | buyerLastName
94 | totalPrice = amount * pricePerItem
95 | }
96 | }
97 |
98 | //----#### SNIPPET #### - 11
99 | ...
100 | val buyerFullName:String = buyerFirstName + " " +
101 | buyerLastName
102 | val totalPrice:Double = amount * pricePerItem
103 | ...
104 |
105 | //----#### SNIPPET #### - 12
106 | val firstInvoice = Invoice("Richard", "Smith",
107 | "2018-10-23", "Peas", 5, 2.99)
108 |
109 | //----#### SNIPPET #### - 13
110 | class Invoice(val buyerFirstName:String,
111 | val buyerLastName:String,
112 | val date:String,
113 | val goodName:String,
114 | val amount:Int,
115 | val pricePerItem:Double)
116 | {
117 | val buyerFullName:String
118 | val totalPrice:Double
119 | init {
120 | buyerFullName = buyerFirstName + " " +
121 | buyerLastName
122 | totalPrice = amount * pricePerItem
123 | }
124 | }
125 |
126 | fun main(args:Array) {
127 | val firstInvoice = Invoice("Richard", "Smith",
128 | "2018-10-23", "Peas", 5, 2.99)
129 | // do something with it...
130 | }
131 |
132 | //----#### SNIPPET #### - 14
133 | ...
134 | val firstInvoice = Invoice("Richard", "Smith",
135 | "2018-10-23", "Peas", 5, 2.99)
136 | val fullName = firstInvoice.buyerFullName
137 |
138 | //----#### SNIPPET #### - 15
139 | ...
140 | val firstInvoice = Invoice("Richard", "Smith",
141 | "2018-10-23", "Peas", 5, 2.99)
142 | firstInvoice.buyerLastName = "Doubtfire"
143 |
144 | //----#### SNIPPET #### - 16
145 | class Invoice( [constructor parameters] ) {
146 | val buyerFullName:String
147 | val totalPrice:Double
148 | init { [initializer code] }
149 |
150 | fun getState(): String {
151 | return "First name: ${firstName}\n" +
152 | "Last name: ${lastName}\n" +
153 | "Full name: ${buyerFullName}\n" +
154 | "Date: ${date}\n" +
155 | "Good: ${goodName}\n" +
156 | "Amount: ${amount}\n" +
157 | "Price per item: ${pricePerItem}\n" +
158 | "Total price: ${totalPrice}"
159 | }
160 | }
161 |
162 | //----#### SNIPPET #### - 17
163 | objectName.functionName(parameter1, parameter2, ...)
164 |
165 | //----#### SNIPPET #### - 18
166 | ...
167 | val firstInvoice = Invoice("Richard", "Smith",
168 | "2018-10-23", "Peas", 5, 2.99)
169 | val state:String = firstInvoice.getState()
170 |
171 | //----#### SNIPPET #### - 19
172 | ...
173 | // we are inside the Invoice class
174 | val state:String = getState()
175 |
176 | //----#### SNIPPET #### - 20
177 | fun tax(taxRate:Double):Double {
178 | return taxRate * amount * pricePerItem
179 | }
180 |
181 | //----#### SNIPPET #### - 21
182 | ...
183 | val firstInvoice = Invoice("Richard", "Smith",
184 | "2018-10-23", "Peas", 5, 2.99)
185 | val tax:Double = firstInvoice.tax(0.11)
186 |
187 | //----#### SNIPPET #### - 22
188 | class Invoice(val buyerFirstName:String,
189 | val buyerLastName:String,
190 | val date:String,
191 | val goodName:String,
192 | val amount:Int,
193 | val pricePerItem:Double)
194 | {
195 | val buyerFullName:String
196 | val totalPrice:Double
197 |
198 | init {
199 | buyerFullName = buyerFirstName + " " +
200 | buyerLastName
201 | totalPrice = amount * pricePerItem
202 | }
203 |
204 | fun getState():String {
205 | return "First name: ${buyerFirstName}\n" +
206 | "Last name: ${buyerLastName}\n" +
207 | "Full name: ${buyerFullName}\n" +
208 | "Date: ${date}\n" +
209 | "Good: ${goodName}\n" +
210 | "Amount: ${amount}\n" +
211 | "Price per item: ${pricePerItem}\n" +
212 | "Total price: ${totalPrice}"
213 | }
214 |
215 | fun tax(taxRate:Double):Double {
216 | return taxRate * amount * pricePerItem
217 | }
218 | }
219 |
220 | fun main(args:Array) {
221 | val firstInvoice = Invoice("Richard", "Smith",
222 | "2018-10-23", "Peas", 5, 2.99)
223 | val state:String = firstInvoice.getState()
224 | val tax:Double = firstInvoice.tax(0.11)
225 | // do more things with it...
226 | }
227 |
--------------------------------------------------------------------------------
/020/src_chapt02_sect002_A_Simple_Number_Guessing_Game.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 02:
3 | //// Classes And Objects: Object Orientation Philosophy
4 | //// Section: 2. A Simple Number Guessing Game
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 |
11 |
12 | NumberGuess
13 |
14 | NumberGuess
15 |
16 | Start
17 |
18 | Guess a number:
19 |
20 | Do guess!
21 |
22 | Number
23 |
24 | Press START to start a game
25 |
26 | Log:
27 |
28 | Guess a number between %1$d and %2$d
29 |
30 | Sorry, too low.
31 |
32 | Sorry, too high.
33 |
34 | You got it after %1$d tries!
35 | Press START for a new game.
36 |
37 |
38 | //----#### SNIPPET #### - 2
39 |
40 |
53 |
54 |
59 |
60 |
66 |
67 |
69 |
70 |
74 |
77 |
84 |
90 |
91 |
92 |
94 |
95 |
102 |
103 |
105 |
106 |
110 |
114 |
115 |
116 |
117 | //----#### SNIPPET #### - 3
118 | package kotlinforandroid.book.numberguess
119 |
120 | import android.content.Context
121 | import android.support.v7.app.AppCompatActivity
122 | import android.os.Bundle
123 | import android.util.AttributeSet
124 | import android.util.Log
125 | import android.view.View
126 | import android.widget.ScrollView
127 | import android.widget.TextView
128 | import kotlinx.android.synthetic.main.activity_main.*
129 |
130 | class MainActivity : AppCompatActivity() {
131 | var started = false
132 | var number = 0
133 | var tries = 0
134 |
135 | override fun onCreate(savedInstanceState: Bundle?) {
136 | super.onCreate(savedInstanceState)
137 | setContentView(R.layout.activity_main)
138 |
139 | fetchSavedInstanceData(savedInstanceState)
140 | doGuess.setEnabled(started)
141 | }
142 |
143 | override fun onSaveInstanceState(outState: Bundle?) {
144 | super.onSaveInstanceState(outState)
145 | putInstanceData(outState)
146 | }
147 |
148 | fun start(v: View) {
149 | log("Game started")
150 | num.setText("")
151 | started = true
152 | doGuess.setEnabled(true)
153 | status.text = getString(R.string.guess_hint, 1, 7)
154 |
155 | number = 1 + Math.floor(Math.random()*7).toInt()
156 | tries = 0
157 | }
158 |
159 | fun guess(v:View) {
160 | if(num.text.toString() == "") return
161 | tries++
162 | log("Guessed ${num.text} (tries:${tries})")
163 | val g = num.text.toString().toInt()
164 | if(g < number) {
165 | status.setText(R.string.status_too_low)
166 | num.setText("")
167 | } else if(g > number){
168 | status.setText(R.string.status_too_high)
169 | num.setText("")
170 | } else {
171 | status.text = getString(R.string.status_hit,
172 | tries)
173 | started = false
174 | doGuess.setEnabled(false)
175 | }
176 | }
177 |
178 | ///////////////////////////////////////////////////
179 | ///////////////////////////////////////////////////
180 |
181 | private fun putInstanceData(outState: Bundle?) {
182 | if (outState != null) with(outState) {
183 | putBoolean("started", started)
184 | putInt("number", number)
185 | putInt("tries", tries)
186 | putString("statusMsg", status.text.toString())
187 | putStringArrayList("logs",
188 | ArrayList(console.text.split("\n")))
189 | }
190 | }
191 |
192 | private fun fetchSavedInstanceData(
193 | savedInstanceState: Bundle?) {
194 | if (savedInstanceState != null)
195 | with(savedInstanceState) {
196 | started = getBoolean("started")
197 | number = getInt("number")
198 | tries = getInt("tries")
199 | status.text = getString("statusMsg")
200 | console.text = getStringArrayList("logs")!!.
201 | joinToString("\n")
202 | }
203 | }
204 |
205 | private fun log(msg:String) {
206 | Log.d("LOG", msg)
207 | console.log(msg)
208 | }
209 | }
210 |
211 | class Console(ctx:Context, aset:AttributeSet? = null)
212 | : ScrollView(ctx, aset) {
213 | val tv = TextView(ctx)
214 | var text:String
215 | get() = tv.text.toString()
216 | set(value) { tv.setText(value) }
217 | init {
218 | setBackgroundColor(0x40FFFF00)
219 | addView(tv)
220 | }
221 | fun log(msg:String) {
222 | val l = tv.text.let {
223 | if(it == "") listOf() else it.split("\n")
224 | }.takeLast(100) + msg
225 | tv.text = l.joinToString("\n")
226 | post(object : Runnable {
227 | override fun run() {
228 | fullScroll(ScrollView.FOCUS_DOWN)
229 | }
230 | })
231 | }
232 | }
233 |
--------------------------------------------------------------------------------
/020/src_chapt02_sect003_Constructors.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 02:
3 | //// Classes And Objects: Object Orientation Philosophy
4 | //// Section: 3. Constructors
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | class ClassName(Parameter-Declaration1,
10 | Parameter-Declaration2, ...) {
11 | [Class-Body]
12 | }
13 |
14 | //----#### SNIPPET #### - 2
15 | Variable-Name:Variable-Type
16 |
17 | //----#### SNIPPET #### - 3
18 | val Variable-Name:Variable-Type
19 |
20 | //----#### SNIPPET #### - 4
21 | var Variable-Name:Variable-Type
22 |
23 | //----#### SNIPPET #### - 5
24 | class ClassName [modifiers] constructor(
25 | Parameter-Declaration1,
26 | Parameter-Declaration2, ...)
27 | {
28 | [Class-Body]
29 | }
30 |
31 | //----#### SNIPPET #### - 6
32 | class GameUser(val firstName:String,
33 | val lastName:String,
34 | val birthday:String,
35 | val userName:String,
36 | val registrationNumber:Int,
37 | val userRank:Double) {
38 | }
39 |
40 | //----#### SNIPPET #### - 7
41 | ...
42 | val firstUser = GameUser("Richard", "Smith",
43 | "2008-10-23", "rsmith", 123, 0.0)
44 |
45 | //----#### SNIPPET #### - 8
46 | val instance = TheClass(
47 | parameterName1 = [some value],
48 | parameterName2 = [some value],
49 | ...)
50 |
51 | //----#### SNIPPET #### - 9
52 | ...
53 | val user = GameUser(
54 | lastName = "Smith",
55 | firstName = "Richard",
56 | birthday = "2098-10-23",
57 | userName = "rsmith",
58 | registrationNumber = 765,
59 | userRank = 0.5)
60 |
61 | //----#### SNIPPET #### - 10
62 | class GameUser(val firstName:String,
63 | val lastName:String,
64 | val userName:String,
65 | val registrationNumber:Int,
66 | val birthday:String = "1900-01-01",
67 | val userRank:Double = 0.0) {
68 | }
69 |
70 | //----#### SNIPPET #### - 11
71 | ...
72 | val firstUser = GameUser("Richard", "Smith",
73 | "rsmith", 123, "2008-10-23", 0.4)
74 |
75 | //----#### SNIPPET #### - 12
76 | ...
77 | val firstUser = GameUser("Richard", "Smith",
78 | "rsmith", 123, "2008-10-23")
79 |
80 | //----#### SNIPPET #### - 13
81 | ...
82 | val firstUser = GameUser("Richard", "Smith",
83 | "rsmith", 123)
84 |
85 | //----#### SNIPPET #### - 14
86 | ...
87 | val firstUser = GameUser(firstName = "Richard",
88 | lastName = "Smith",
89 | userName = "rsmith",
90 | registrationNumber = 123)
91 |
92 | //----#### SNIPPET #### - 15
93 | constructor(param1:ParamType1,
94 | param2:ParamType2, ...)
95 | {
96 | // do some things...
97 | }
98 |
99 | //----#### SNIPPET #### - 16
100 | constructor(param1:ParamType1,
101 | param2:ParamType2, ...) : this(...) {
102 | // do some things...
103 | }
104 |
105 | //----#### SNIPPET #### - 17
106 | constructor(firstName:String,
107 | lastName:String,
108 | userName:String,
109 | registrationNumber:Int) :
110 | this(firstName = firstName,
111 | lastName = lastName,
112 | userName = userName,
113 | registrationNumber = registrationNumber,
114 | birthday = "",
115 | userRank = 0.0
116 | )
117 | {
118 | // constructor body
119 | // do some things...
120 | }
121 |
122 | //----#### SNIPPET #### - 18
123 | ...
124 | val firstUser = GameUser(firstName = "Richard",
125 | lastName = "Smith",
126 | userName = "rsmith",
127 | registrationNumber = 123)
128 |
--------------------------------------------------------------------------------
/020/src_chapt02_sect004_If_Classes_Are_Not_Needed__Singleton_Objects.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 02:
3 | //// Classes And Objects: Object Orientation Philosophy
4 | //// Section: 4. If Classes Are Not Needed: Singleton Objects
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | object ObjectName {
10 | [Object-Body]
11 | }
12 |
13 | //----#### SNIPPET #### - 2
14 | ObjectName.propertyName
15 | ObjectName.function([function-parameters])
16 |
17 | //----#### SNIPPET #### - 3
18 | status.text = getString(R.string.guess_hint, 1, 7)
19 | number = 1 + Math.floor(Math.random()*7).toInt()
20 |
21 | //----#### SNIPPET #### - 4
22 | object Constants {
23 | val LOWER_BOUND = 1
24 | val UPPER_BOUND = 7
25 | }
26 |
27 | //----#### SNIPPET #### - 5
28 | status.text = getString(R.string.guess_hint,
29 | Constants.LOWER_BOUND,
30 | Constants.UPPER_BOUND)
31 | val span = Constants.UPPER_BOUND -
32 | Constants.LOWER_BOUND + 1
33 | number = Constants.LOWER_BOUND +
34 | Math.floor(Math.random()*span).toInt()
35 |
36 | //----#### SNIPPET #### - 6
37 | fun start(v: View) {
38 | log("Game started")
39 | num.setText("")
40 | started = true
41 | doGuess.setEnabled(true)
42 | status.text = getString(R.string.guess_hint,
43 | Constants.LOWER_BOUND,
44 | Constants.UPPER_BOUND)
45 |
46 | val span = Constants.UPPER_BOUND -
47 | Constants.LOWER_BOUND + 1
48 | number = Constants.LOWER_BOUND +
49 | Math.floor(Math.random()*span).toInt()
50 | tries = 0
51 | }
52 |
--------------------------------------------------------------------------------
/020/src_chapt02_sect005_If_State_Doesn_t_Matter__Companion_Objects.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 02:
3 | //// Classes And Objects: Object Orientation Philosophy
4 | //// Section: 5. If State Doesn’t Matter: Companion Objects
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | companion object ObjectName {
10 | ...
11 | }
12 |
13 | //----#### SNIPPET #### - 2
14 | class TheClass {
15 | companion object ObjectName {
16 | val SOME_CONSTANT: Int = 42
17 | }
18 | ...
19 | fun someFunction() {
20 | val x = 7 * SOME_CONSTANT
21 | ...
22 | }
23 | }
24 |
25 | //----#### SNIPPET #### - 3
26 | class Console(ctx:Context, aset:AttributeSet? = null)
27 | : ScrollView(ctx, aset) {
28 | companion object {
29 | val BACKGROUND_COLOR = 0x40FFFF00
30 | val MAX_LINES = 100
31 | }
32 | val tv = TextView(ctx)
33 | var text:String
34 | get() = tv.text.toString()
35 | set(value) { tv.setText(value) }
36 | init {
37 | setBackgroundColor(BACKGROUND_COLOR)
38 | addView(tv)
39 | }
40 | fun log(msg:String) {
41 | val l = tv.text.let {
42 | if(it == "") listOf() else it.split("\n") }.
43 | takeLast(MAX_LINES) + msg
44 | tv.text = l.joinToString("\n")
45 | post(object : Runnable {
46 | override fun run() {
47 | fullScroll(ScrollView.FOCUS_DOWN)
48 | }
49 | })
50 | }
51 | }
52 |
53 | //----#### SNIPPET #### - 4
54 | TheClass.THE_PROPERTY
55 | TheClass.someFunction()
56 |
--------------------------------------------------------------------------------
/020/src_chapt02_sect006_Describing_a_Contract__Interfaces.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 02:
3 | //// Classes And Objects: Object Orientation Philosophy
4 | //// Section: 6. Describing a Contract: Interfaces
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | interface GraphicsObject {
10 | fun numberOfCorners(): Int
11 | fun coordsOf(index:Int): Pair
12 | fun fillColor(): String
13 | }
14 |
15 | //----#### SNIPPET #### - 2
16 | class Triangle : GraphicsObject {
17 | override fun numberOfCorners(): Int {
18 | return 3
19 | }
20 | override fun coordsOf(index:Int):
21 | Pair {
22 | return when(index) {
23 | 0 -> Pair(-1.0, 0.0)
24 | 1 -> Pair(1.0, 0.0)
25 | 2 -> Pair(0.0, 1.0)
26 | else throw RuntimeException(
27 | "Index ${index} out of bounds")
28 | }
29 | }
30 | override fun fillColor(): String {
31 | return "red"
32 | }
33 | }
34 |
35 | //----#### SNIPPET #### - 3
36 | class Triangle : GraphicsObject {
37 | override fun numberOfCorners() = 3
38 | override fun coordsOf(index:Int) =
39 | when(index) {
40 | 0 -> Pair(-1.0, 0.0)
41 | 1 -> Pair(1.0, 0.0)
42 | 2 -> Pair(0.0, 1.0)
43 | else -> throw RuntimeException(
44 | "Index ${index} out of bounds")
45 | }
46 | override fun fillColor() = "red"
47 | }
48 |
49 | //----#### SNIPPET #### - 4
50 | class Collector {
51 | ...
52 | fun add(graphics:GraphicsObject) {
53 | // do something with it...
54 | }
55 | }
56 |
57 | //----#### SNIPPET #### - 5
58 | ...
59 | val collector = [get hold of it]
60 | val triang:GraphicsObject = Triangle()
61 | collector.add(triang)
62 | ...
63 |
64 | //----#### SNIPPET #### - 6
65 | interface GraphicsObject {
66 | fun numberOfCorners(): Int
67 | fun coordsOf(index:Int): Pair
68 | fun fillColor(): String
69 | }
70 |
71 | object Collector {
72 | fun add(graphics:GraphicsObject) {
73 | println("Collector.add():")
74 | println("Number of corners: " +
75 | graphics.numberOfCorners())
76 | println("Color: " +
77 | graphics.fillColor())
78 | }
79 | }
80 |
81 | //----#### SNIPPET #### - 7
82 | class Triangle : GraphicsObject {
83 | override fun numberOfCorners() = 3
84 | override fun coordsOf(index:Int) =
85 | when(index) {
86 | 0 -> Pair(-1.0, 0.0)
87 | 1 -> Pair(1.0, 0.0)
88 | 2 -> Pair(0.0, 1.0)
89 | else -> throw RuntimeException(
90 | "Index ${index} out of bounds")
91 | }
92 | override fun fillColor() = "red"
93 | }
94 |
95 | fun main(args:Array) {
96 | val collector = Collector
97 | val triang:GraphicsObject = Triangle()
98 | collector.add(triang)
99 | }
100 |
--------------------------------------------------------------------------------
/020/src_chapt02_sect007_Structuring_And_Packages.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 02:
3 | //// Classes And Objects: Object Orientation Philosophy
4 | //// Section: 7. Structuring And Packages
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | package the.hierarchical.position
10 | ...
11 |
12 | //----#### SNIPPET #### - 2
13 | package kotlinforandroid.book.numberguess.random.impl
14 |
15 | class RandomRandom {
16 | ...
17 | }
18 |
19 | //----#### SNIPPET #### - 3
20 | package kotlinforandroid.book.numberguess
21 |
22 | import kotlinforandroid.book.numberguess.gui.Console
23 |
24 | class Activity {
25 | ...
26 | }
27 |
28 | //----#### SNIPPET #### - 4
29 | package kotlinforandroid.book.numberguess
30 |
31 | import kotlinforandroid.book.numberguess.gui.Console
32 | import kotlinforandroid.book.numberguess.common.
33 | Constants
34 |
35 | class Activity {
36 | ...
37 | }
38 |
39 | //----#### SNIPPET #### - 5
40 | package kotlinforandroid.book.numberguess
41 |
42 | import kotlinforandroid.book.numberguess.
43 | random.impl.*
44 |
45 | class Activity {
46 | ...
47 | }
48 |
--------------------------------------------------------------------------------
/030/src_chapt03_sect001_Properties_And_Their_Types.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 03:
3 | //// Classes at Work: Properties And Functions
4 | //// Section: 1. Properties And Their Types
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | [visibility] [modifiers] val propertyName:PropertyType
10 | = initial_value
11 | [visibility] [modifiers] var propertyName:PropertyType
12 | = initial_value
13 |
14 | //----#### SNIPPET #### - 2
15 | val propertyName:PropertyType = initial_value
16 | var propertyName:PropertyType = initial_value
17 |
18 | //----#### SNIPPET #### - 3
19 | class GameUser(val firstName:String,
20 | val lastName:String,
21 | val userName:String,
22 | val registrationNumber:Int,
23 | val birthday:String = "",
24 | val userRank:Double = 0.0) {
25 | val fullName:String
26 | val initials:String
27 | init {
28 | fullName = firstName + " " + lastName
29 | initials = firstName.toUpperCase() +
30 | lastName.toUpperCase()
31 | }
32 | }
33 |
34 | //----#### SNIPPET #### - 4
35 | val user = GameUser("Peter", "Smith", "psmith",
36 | 123, "1988-10-03", 0.79)
37 | val firstName = user.firstName
38 | val fullName = user.fullName
39 |
40 | //----#### SNIPPET #### - 5
41 | class GameUser(var firstName:String,
42 | var lastName:String,
43 | var userName:String,
44 | var registrationNumber:Int,
45 | var birthday:String = "",
46 | var userRank:Double = 0.0) {
47 | var fullName:String
48 | var initials:String
49 | init {
50 | fullName = firstName + " " + lastName
51 | initials = firstName.toUpperCase() +
52 | lastName.toUpperCase()
53 | }
54 | }
55 |
56 | // somewhere inside a function in class MainActivity
57 | val user = GameUser("Peter", "Smith", "psmith",
58 | 123, "1988-10-03", 0.79)
59 | user.firstName = "Linda"
60 | console.log(user.fullName)
61 |
62 | //----#### SNIPPET #### - 6
63 | class TheClassName {
64 | val propertyName1:PropertyType1 = initial_value
65 | var propertyName2:PropertyType2 = initial_value
66 | ...
67 | }
68 |
69 | object SingletonObjectName {
70 | val propertyName1:PropertyType1 = initial_value
71 | var propertyName2:PropertyType2 = initial_value
72 | ...
73 | }
74 |
75 | class TheClassName {
76 | companion object {
77 | val propertyName1:PropertyType1 = initial_value
78 | var propertyName2:PropertyType2 = initial_value
79 | ...
80 | }
81 | }
82 |
83 | //----#### SNIPPET #### - 7
84 | // we are inside a class, a singleton object, or
85 | // a companion object
86 | init {
87 | propertyName1 = initial_value
88 | propertyName2 = initial_value
89 | ...
90 | }
91 |
92 | //----#### SNIPPET #### - 8
93 | // we are inside a class, a singleton object, or
94 | // a companion object
95 | val propertyName1:PropertyType1
96 | var propertyName2:PropertyType2
97 | init {
98 | propertyName1 = initial_value
99 | propertyName2 = initial_value
100 | ...
101 | }
102 |
103 | //----#### SNIPPET #### - 9
104 | // we are inside a class, a singleton object, or
105 | // a companion object
106 | var propertyName1:PropertyType1 = initial_value
107 | ...
108 | fun someFunction() {
109 | propertyName1 = new_value
110 | ...
111 | }
112 |
113 | //----#### SNIPPET #### - 10
114 | instanceName.propertyName = new_value
115 | ObjectName.propertyName = new_value
116 |
117 | //----#### SNIPPET #### - 11
118 | val anInteger = 42
119 | val anotherInteger = anInteger + 7
120 | val aThirdInteger = 0xFF473
121 | val aLongInteger = 700_000_000_000L
122 | val aFloatingPoint = 37.103
123 | val anotherFloatingPoint = -37e-12
124 | val aSinglePrecisionFloat = 1.3f
125 | val aChar = 'A'
126 | val aString = "Hello World"
127 | val aMultiLineString = """First Line
128 | Second Line"""
129 |
130 | //----#### SNIPPET #### - 12
131 | var propertyName:PropertyType? = null
132 |
133 | //----#### SNIPPET #### - 13
134 | var anInteger:Int? = null
135 | var anInstance:SomeClass? = null
136 |
137 | //----#### SNIPPET #### - 14
138 | var anInteger:Int? = 42
139 | anInteger = null
140 |
141 | //----#### SNIPPET #### - 15
142 | var s:String? = "Hello"
143 | val l1 = s?.length() // -> 5
144 | s = null
145 | val l2 = s?.length() // -> null
146 |
147 | //----#### SNIPPET #### - 16
148 | const val name = ...
149 |
150 | //----#### SNIPPET #### - 17
151 | lateinit var name:Type
152 |
153 | //----#### SNIPPET #### - 18
154 | class TheClass {
155 | lateinit var name:String
156 | fun someFunction() {
157 | val stringSize = name.length
158 | }
159 | }
160 |
--------------------------------------------------------------------------------
/030/src_chapt03_sect002_Member_Functions.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 03:
3 | //// Classes at Work: Properties And Functions
4 | //// Section: 2. Member Functions
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | [modifiers]
10 | fun functionName([parameters]) {
11 | [Function Body]
12 | }
13 |
14 | //----#### SNIPPET #### - 2
15 | fun printAdded(param1:Int, param2:Int]) {
16 | console.log(param1 + param2)
17 | }
18 | fun printHello() {
19 | console.log("Hello")
20 | }
21 |
22 | //----#### SNIPPET #### - 3
23 | fun functionName([parameters])
24 |
25 | //----#### SNIPPET #### - 4
26 | [modifiers]
27 | fun functionName([parameters]): ReturnType {
28 | [Function Body]
29 | return [expression]
30 | }
31 |
32 | //----#### SNIPPET #### - 5
33 | fun add37(param:Int): Int {
34 | val retVal = param + 37
35 | return retVal
36 | }
37 |
38 | //----#### SNIPPET #### - 6
39 | [modifiers]
40 | fun functionName([parameters]): ReturnType = [expression]
41 |
42 | //----#### SNIPPET #### - 7
43 | fun add37(param:Int) = param + 37
44 |
45 | //----#### SNIPPET #### - 8
46 | fun functionName([parameters]): ReturnType
47 |
48 | //----#### SNIPPET #### - 9
49 | class A {
50 | val xyz:Int = 7
51 | fun meth1(xyz:Int) {
52 | [Function-Body]
53 | }
54 | }
55 |
56 | //----#### SNIPPET #### - 10
57 | class A {
58 | val xyz:Int = 7
59 | fun meth1(xyz:Int) {
60 | val q1 = xyz // parameter
61 | val q2 = this.xyz // property
62 | ...
63 | }
64 | }
65 |
66 | //----#### SNIPPET #### - 11
67 | instance.functionName([parameters]) // outside the class
68 | functionName([parameters]) // inside the class
69 | Object.functionName([parameters]) // outside the object
70 | functionName([parameters]) // inside the object
71 |
72 | //----#### SNIPPET #### - 12
73 | instance.function(par1 = [value1], par2 = [value2], ...)
74 |
75 | //----#### SNIPPET #### - 13
76 | function(par1 = [value1], par2 = [value2], ...)
77 |
78 | //----#### SNIPPET #### - 14
79 | parameterName:ParameterType = [default value]
80 |
81 | //----#### SNIPPET #### - 15
82 | fun functionName(
83 | param1:ParamType1,
84 | param2:ParamType2,
85 | ...
86 | paramM:ParamTypeM = [default1],
87 | paramM+1:ParamTypeM+1 = [default2],
88 | ...) { ... }
89 |
90 | //----#### SNIPPET #### - 16
91 | fun functionName(
92 | param1:ParamType1,
93 | param2:ParamType2,
94 | ...
95 | paramN:ParamTypeN,
96 | vararg paramV:ParamTypeV) { ... }
97 |
98 | //----#### SNIPPET #### - 17
99 | fun functionName(varargs paramV:ParamTypeV) {
100 | ...
101 | }
102 |
103 | //----#### SNIPPET #### - 18
104 | functionName(param1, param2, ..., paramN,
105 | vararg1, vararg2, ...)
106 |
107 | //----#### SNIPPET #### - 19
108 | fun meth(date:String, vararg names:String) {
109 | ...
110 | }
111 |
112 | //----#### SNIPPET #### - 20
113 | meth("2018-01-23")
114 | meth("2018-01-23", "Gina Eleniak")
115 | meth("2018-01-23", "Gina Eleniak",
116 | "John Smith")
117 | meth("2018-01-23", "Gina Eleniak",
118 | "John Smith", "Brad Cold")
119 |
120 | //----#### SNIPPET #### - 21
121 | meth("2018-01-23", "Gina Eleniak",
122 | "John Smith", "Brad Cold")
123 |
124 | //----#### SNIPPET #### - 22
125 | abstract class TheAbstractClass {
126 | abstract fun function([parameters])
127 | ... more functions ...
128 | }
129 |
130 | //----#### SNIPPET #### - 23
131 | abstract class TheAbstractClass {
132 | abstract fun function([parameters])
133 | ... more functions ...
134 | }
135 |
136 | // A subclass of TheAbstractClass ->
137 | class TheClass : TheAbstractClass() {
138 | override fun function([parameters]) {
139 | // do something...
140 | }
141 | }
142 |
143 | //----#### SNIPPET #### - 24
144 | class Calculator {
145 | fun add(a:Int) {
146 | ...
147 | }
148 | fun add(a:Double) {
149 | ...
150 | }
151 | fun add(a:String) {
152 | ...
153 | }
154 | }
155 |
156 | //----#### SNIPPET #### - 25
157 | fun a() {
158 | fun b() {
159 | ...
160 | }
161 | ...
162 | b()
163 | ...
164 | }
165 |
--------------------------------------------------------------------------------
/030/src_chapt03_sect003_Inheritance.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 03:
3 | //// Classes at Work: Properties And Functions
4 | //// Section: 3. Inheritance
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | open class A { ... }
10 | class B : A() {
11 | [overriding assets]
12 | [own assets]
13 | }
14 |
15 | //----#### SNIPPET #### - 2
16 | open class A([constructor parameters]) { ... }
17 | class B : A([constructor parameters]) {
18 | [overriding assets]
19 | [own assets]
20 | }
21 |
22 | //----#### SNIPPET #### - 3
23 | open class A([constructor parameters]) { ... }
24 | class B([own constructor parameters]) :
25 | A([constructor parameters])
26 | {
27 | [overriding assets]
28 | [own assets]
29 | }
30 |
31 | //----#### SNIPPET #### - 4
32 | open class A([constructor parameters]) {
33 | constructor([parameters2]) { ... }
34 | }
35 | class B : A([parameters2]) {
36 | ...
37 | }
38 |
39 | //----#### SNIPPET #### - 5
40 | open class A(open val a:Int) {
41 | }
42 |
43 | //----#### SNIPPET #### - 6
44 | open class A(open val a:Int) {
45 | }
46 | class B(override val a:Int) : A(42) {
47 | ...
48 | }
49 |
50 | //----#### SNIPPET #### - 7
51 | open class A {
52 | open fun function1() { ... }
53 | }
54 | class B : A() {
55 | override
56 | fun function1() { ... }
57 | }
58 |
59 | //----#### SNIPPET #### - 8
60 | super.functionName(param1, param2, ...)
61 |
62 | //----#### SNIPPET #### - 9
63 | open class A {
64 | open var a:Int = 0
65 | }
66 |
67 | //----#### SNIPPET #### - 10
68 | class B : A() {
69 | override var a:Int = 0
70 | }
71 |
72 | //----#### SNIPPET #### - 11
73 | open class A() {
74 | open var a:Int = 99
75 | open fun x() {
76 | Log.d("LOG", "Hey from A.x()")
77 | }
78 | }
79 |
80 | class B : A() {
81 | override var a:Int = 77
82 | override fun x() {
83 | Log.d("LOG", "Hey from A.x()")
84 | }
85 | fun show() {
86 | Log.d("LOG", "Property: " + a)
87 | Log.d("LOG", "Formerly: " + super.a)
88 | Log.d("LOG", "Function: ")
89 | x()
90 | Log.d("LOG", "Formerly: ")
91 | super.x()
92 | }
93 | }
94 |
95 | // inside some activity function:
96 | val b = B()
97 | b.show()
98 |
--------------------------------------------------------------------------------
/030/src_chapt03_sect004_Local_Variables.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 03:
3 | //// Classes at Work: Properties And Functions
4 | //// Section: 4. Local Variables
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | class TheClass {
10 | fun function() {
11 | ...
12 | var localVar1:Int = 7
13 | val localVar1:Int = 8
14 | ...
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/030/src_chapt03_sect005_Visibility_of_Classes_And_Class_Members.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 03:
3 | //// Classes at Work: Properties And Functions
4 | //// Section: 5. Visibility of Classes And Class Members
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | class TheName { // or object or companion object
10 | val prop1:Type1
11 | var prop2:Type2
12 | fun function() {
13 | ...
14 | }
15 | }
16 |
17 | //----#### SNIPPET #### - 2
18 | public [class or (companion) object] TheName {
19 | public val prop1:Type1
20 | public var prop2:Type2
21 | public fun function() {
22 | ...
23 | }
24 | }
25 |
26 | //----#### SNIPPET #### - 3
27 | class Clock {
28 | fun time(): String {
29 | ...
30 | }
31 | fun setTime(time:String) {
32 | ...
33 | }
34 | }
35 |
36 | //----#### SNIPPET #### - 4
37 | class Clock {
38 | var hourAngle:Double = 0
39 | var minuteAngle:Double = 0
40 | var secondsAngle:Double = 0
41 | var timer:Timer = Timer()
42 |
43 | init {
44 | ...
45 | }
46 |
47 | fun time(): String {
48 | ...
49 | }
50 |
51 | fun setTime(time:String) {
52 | ...
53 | }
54 |
55 | fun adjustTime(minutes:Int) {
56 | ...
57 | }
58 |
59 | fun tick() {
60 | ...
61 | }
62 | }
63 |
64 | //----#### SNIPPET #### - 5
65 | class Clock {
66 | private var hourAngle:Double = 0
67 | private var minuteAngle:Double = 0
68 | private var secondsAngle:Double = 0
69 | private var timer:Timer = Timer()
70 |
71 | init {
72 | ...
73 | }
74 |
75 | fun time(): String {
76 | ...
77 | }
78 |
79 | fun setTime(time:String) {
80 | ...
81 | }
82 |
83 | private fun adjustTime(minutes:Int) {
84 | ...
85 | }
86 |
87 | private fun tick() {
88 | ...
89 | }
90 | }
91 |
92 | //----#### SNIPPET #### - 6
93 | class MainActivity : AppCompatActivity() {
94 | override fun onCreate(savedInstanceState: Bundle?)
95 | override fun onSaveInstanceState(outState: Bundle?)
96 | fun start(v: View)
97 | fun guess(v:View)
98 |
99 | ///////////////////////////////////////////////////
100 | ///////////////////////////////////////////////////
101 |
102 | private fun putInstanceData(outState: Bundle?)
103 | private fun fetchSavedInstanceData(
104 | savedInstanceState: Bundle?)
105 | private fun log(msg:String)
106 | }
107 |
108 | //----#### SNIPPET #### - 7
109 | class A {
110 | private class B {
111 | ... }
112 | fun function() {
113 | val b = B()
114 | }
115 | }
116 |
117 | //----#### SNIPPET #### - 8
118 | class A {
119 | protected class B {
120 | ... }
121 | fun function() {
122 | val b = B()
123 | }
124 | }
125 | class AA : A {
126 | // subclass of A
127 | fun function() {
128 | val b = B()
129 | }
130 | }
131 |
--------------------------------------------------------------------------------
/030/src_chapt03_sect006_Self_Reference__This.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 03:
3 | //// Classes at Work: Properties And Functions
4 | //// Section: 6. Self-Reference: This
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | functionName() -the same as- this.functionName()
10 | propertyName -the same as- this.propertyName
11 |
12 | //----#### SNIPPET #### - 2
13 | var firstName:String = ""
14 | var lastName:String = ""
15 | var socialSecurityNumber:String = ""
16 | ...
17 | fun set(fName:String, lName:String, ssn:String) {
18 | this.lastName = lName
19 | this.firstName = fName
20 | this.socialSecurityNumber = ssn
21 | }
22 |
--------------------------------------------------------------------------------
/030/src_chapt03_sect007_Converting_Classes_to_Strings.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 03:
3 | //// Classes at Work: Properties And Functions
4 | //// Section: 7. Converting Classes to Strings
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | class Line(val x1:Double, val y1:Double,
10 | val x2:Double, val y2:Double) {
11 | {
12 | override fun toString() =
13 | "(${x1},${y1}) -> (${x2},${y2})"
14 | }
15 |
16 | //----#### SNIPPET #### - 2
17 | class Line(val x1:Double, val y1:Double,
18 | val x2:Double, val y2:Double) {
19 | {
20 | override fun toString() = super.toString()
21 | " (${x1},${y1}) -> (${x2},${y2})"
22 | }
23 |
24 | //----#### SNIPPET #### - 3
25 | class A
26 | val a = A()
27 | println(a.toString())
28 |
--------------------------------------------------------------------------------
/040/src_chapt04_sect001_Anonymous_Classes.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 04:
3 | //// Classes And Objects: Extended Features
4 | //// Section: 1. Anonymous Classes
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | class A : SomeInterface {
10 | // implement interface functions...
11 | }
12 | val inst:SomeInterface = A()
13 | // use inst...
14 |
15 | //----#### SNIPPET #### - 2
16 | open class A : SomeBaseClass() {
17 | // override functions...
18 | }
19 | val inst:SomeBaseClass = A()
20 | // use inst...
21 |
22 | //----#### SNIPPET #### - 3
23 | val inst:SomeInterface = object : SomeInterface {
24 | // implement interface functions...
25 | }
26 | // use inst...
27 |
28 | //----#### SNIPPET #### - 4
29 | val inst:SomeBaseClass = object : SomeBaseClass() {
30 | // override functions...
31 | }
32 | // use inst...
33 |
34 | //----#### SNIPPET #### - 5
35 | interface X {
36 | fun doSomething()
37 | }
38 | class A {
39 | fun meth() {
40 | val x = object : X {
41 | override doSomething() {
42 | println(this)
43 | println(this@A)
44 | }
45 | }
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/040/src_chapt04_sect002_Inner_Classes.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 04:
3 | //// Classes And Objects: Extended Features
4 | //// Section: 2. Inner Classes
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | class A {
10 | class B { ... }
11 | // B can now be instantiated from
12 | // everywhere inside A
13 | fun meth() {
14 | ...
15 | class C { ... }
16 | // C can now be used until the end of
17 | // the function
18 | ...
19 | }
20 | }
21 |
22 | //----#### SNIPPET #### - 2
23 | class A {
24 | class B { ... }
25 | }
26 | fun main(args:Array) {
27 | val ab = A.B()
28 | // do something with it...
29 | }
30 |
--------------------------------------------------------------------------------
/040/src_chapt04_sect004_Importing_Functions_And_Properties.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 04:
3 | //// Classes And Objects: Extended Features
4 | //// Section: 4. Importing Functions And Properties
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | import package.of.the.object.ObjectName.propertyName
10 | import package.of.the.object.ObjectName.functionName
11 |
--------------------------------------------------------------------------------
/040/src_chapt04_sect005_Data_Classes.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 04:
3 | //// Classes And Objects: Extended Features
4 | //// Section: 5. Data Classes
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | data class ClassName([constructor])
10 |
11 | //----#### SNIPPET #### - 2
12 | data class Point(val x:Double, val y:Double)
13 |
14 | fun movePoint(pt:Point, dx:Double, dy:Double):Point =
15 | Point(pt.x + dx, pt.y + dy)
16 |
17 | // somewhere in a function...
18 | val pt = Point(0.0, 1.0)
19 | val pt2 = movePoint(pt, 0.5, 0.5)
20 |
--------------------------------------------------------------------------------
/040/src_chapt04_sect006_Enumerations.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 04:
3 | //// Classes And Objects: Extended Features
4 | //// Section: 6. Enumerations
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | enum class EnumerationName {
10 | VALUE1, VALUE2, VALUE3, ...
11 | }
12 |
13 | //----#### SNIPPET #### - 2
14 | val e1: EnumerationName = ...
15 | var e2: EnumerationName = ...
16 |
17 | //----#### SNIPPET #### - 3
18 | enum class Fruit {
19 | BANANA, APPLE, PINEAPPLE, GRAPE
20 | }
21 |
22 | val f1 = Fruit.BANANA
23 | val f2 = Fruit.BANANA
24 | val f3 = Fruit.APPLE
25 | var fx:Fruit? = null
26 |
27 | // you can check for equality:
28 | val b1:Boolean = f1 == f2 // -> true
29 | val b2:Boolean = f1 == f3 // -> false
30 |
31 | // you can reassign vars:
32 | fx = Fruit.APPLE
33 | fx = Fruit.BANANA
34 |
35 | // toString() gives the textual value name
36 | val s = fx.toString() // -> "BANANA"
37 |
38 | //----#### SNIPPET #### - 4
39 | enum class Fruit(val fruitName:String) {
40 | BANANA("banana"),
41 | APPLE("apple"),
42 | PINEAPPLE("pineapple"),
43 | GRAPE("grape")
44 | }
45 |
46 | //----#### SNIPPET #### - 5
47 | val f1 = Fruit.BANANA
48 | var internalVal = f1.fruitName // -> "banana"
49 |
50 | //----#### SNIPPET #### - 6
51 | val f1 = Fruit.valueOf("BANANA")
52 | // <- same as Fruit.BANANA
53 |
54 | //----#### SNIPPET #### - 7
55 | EnumerationName.values()
56 |
--------------------------------------------------------------------------------
/040/src_chapt04_sect007_Custom_Property_Accessors.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 04:
3 | //// Classes And Objects: Extended Features
4 | //// Section: 7. Custom Property Accessors
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | var propertyName:PropertyType = [initial_value]
10 |
11 | //----#### SNIPPET #### - 2
12 | var propertyName:PropertyType = [initial_value]
13 | get() = [getting_expression]
14 |
15 | //----#### SNIPPET #### - 3
16 | var propertyName:PropertyType = [initial_value]
17 | get() {
18 | ...
19 | return [expression]
20 | }
21 |
22 | //----#### SNIPPET #### - 4
23 | var propertyName:PropertyType = [initial_value]
24 | set(value) { ... }
25 |
26 | //----#### SNIPPET #### - 5
27 | var propertyName:PropertyType = [initial_value]
28 | get() = [getting_expression]
29 | set(value) { ... }
30 |
31 | //----#### SNIPPET #### - 6
32 | [modifier] var propertyName:PropertyType = ...
33 | private get
34 | private set
35 |
--------------------------------------------------------------------------------
/040/src_chapt04_sect008_Kotlin_Extensions.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 04:
3 | //// Classes And Objects: Extended Features
4 | //// Section: 8. Kotlin Extensions
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | package the.ext.pckg
10 |
11 | fun String.hasLength(len:Int) = this.length == len
12 |
13 | //----#### SNIPPET #### - 2
14 | import the.ext.pckg.*
15 |
16 | // anywhere inside a function...
17 | val hasLen10:Boolean = someString.hasLength(10)
18 |
19 | //----#### SNIPPET #### - 3
20 | package the.ext.pckg
21 |
22 | val String.l get() = this.length
23 |
24 | //----#### SNIPPET #### - 4
25 | import the.ext.pckg.*
26 |
27 | // anywhere inside a function...
28 | val len1 = someString.length
29 | val len2 = someString.l // this is the same
30 |
31 | //----#### SNIPPET #### - 5
32 | fun SomeClass?.newFunction(...) { ... }
33 |
34 | //----#### SNIPPET #### - 6
35 | class SomeClass {
36 | fun SomeOtherClass.meth() {
37 | ...
38 | }
39 | }
40 |
41 | //----#### SNIPPET #### - 7
42 | class SomeClass {
43 | fun String.hasLength(len:Int) = this.length == len
44 | fun function() {
45 | ...
46 | // we can use hasLength() here
47 | val len10:Boolean = someString.hasLength(10)
48 | ...
49 | }
50 | }
51 |
52 | class SomeClass2 {
53 | // we can't use String.hasLength() here
54 | }
55 |
56 | //----#### SNIPPET #### - 8
57 | class SomeClass {
58 | val SomeOtherClass.prop get() = ...
59 | }
60 |
61 | //----#### SNIPPET #### - 9
62 | class SomeClass {
63 | val String.l get() = this.length
64 | fun function() {
65 | ...
66 | // we can use .l here
67 | val len = someString.l
68 | ...
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/040/src_chapt04_sect009_Functions_With_Tail_Recursion.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 04:
3 | //// Classes And Objects: Extended Features
4 | //// Section: 9. Functions With Tail Recursion
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | fun factorial(n:Int):Int {
10 | return if(n==1) n else n * factorial(n-1)
11 | }
12 |
13 | //----#### SNIPPET #### - 2
14 | tailrec fun factorial(n:Int) {
15 | return if(n==1) n else n * factorial(n-1)
16 | }
17 |
--------------------------------------------------------------------------------
/040/src_chapt04_sect010_Infix_Operators.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 04:
3 | //// Classes And Objects: Extended Features
4 | //// Section: 10. Infix Operators
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | infix operator
10 | fun SomeClass1.oper(param:SomeClass2) = ...
11 |
12 | //----#### SNIPPET #### - 2
13 | [expression1] oper [expression2]
14 |
15 | //----#### SNIPPET #### - 3
16 | infix operator
17 | fun SomeClass1.oper(param:SomeClass2):ResultType {
18 | ...
19 | return [result_expression]
20 | }
21 |
22 | //----#### SNIPPET #### - 4
23 | infix operator fun String.TIMES(i:Int) =
24 | (1..i).map { this }.joinToString("")
25 |
26 | //----#### SNIPPET #### - 5
27 | val s = "abc" TIMES 3 // -> "abcabcabc"
28 |
29 | //----#### SNIPPET #### - 6
30 | operator fun String.times(i:Int) =
31 | (1..i).map { this }.joinToString("")
32 |
33 | //----#### SNIPPET #### - 7
34 | val s = "abc" * 3 // -> "abcabcabc"
35 |
--------------------------------------------------------------------------------
/040/src_chapt04_sect011_Operator_Overloading.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 04:
3 | //// Classes And Objects: Extended Features
4 | //// Section: 11. Operator Overloading
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | data class Point(val x:Double, val y:Double)
10 | data class Vector(val dx:Double, val dy:Double)
11 |
12 | //----#### SNIPPET #### - 2
13 | val p1 = Point(1.0, 1.0)
14 | val p2 = Point(4.0, -2.0)
15 | val v:Vector = p2 - p1
16 |
17 | //----#### SNIPPET #### - 3
18 | data class Point(val x:Double, val y:Double) {
19 | operator fun minus(p2:Point) =
20 | Vector(p2.x-this.x, p2.y-this.y)
21 | }
22 |
23 | //----#### SNIPPET #### - 4
24 | operator fun unaryMinus() = Vector(-this.dx, -this.dy)
25 |
26 | //----#### SNIPPET #### - 5
27 | operator fun Point.minus(p2:Point) =
28 | Vector(p2.x-this.x, p2.y-this.y)
29 |
--------------------------------------------------------------------------------
/040/src_chapt04_sect012_Delegation.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 04:
3 | //// Classes And Objects: Extended Features
4 | //// Section: 12. Delegation
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | interface TheInterface {
10 | fun someMethod(i:Int):Int
11 | ...more functions
12 | }
13 |
14 | class Implementor0 : SomeInterface {
15 | override fun someMethod(i:Int):Int = i*2
16 | ...implement the other functions
17 | }
18 |
19 | class Implementor : TheInterface {
20 | val delegate = Implementor0()
21 | override fun someMethod(i:Int):Int = delegate(i)
22 | ...do the same for the other functions
23 | }
24 |
25 | //----#### SNIPPET #### - 2
26 | override fun someMethod(i:Int):Int = delegate(i-1) + 1
27 |
28 | //----#### SNIPPET #### - 3
29 | class Implementor : TheInterface by Implementor0()
30 | // or
31 | val impl0 = Implementor0()
32 | class Implementor : TheInterface by impl0
33 |
34 | //----#### SNIPPET #### - 4
35 | class Implementor : TheInterface by Implementor0() {
36 | override fun someMethod(i:Int):Int = i * 42
37 | }
38 |
39 | //----#### SNIPPET #### - 5
40 | val b = Implementor0()
41 | class Implementor(val b:TheInterface) :
42 | TheInterface by b {
43 | override
44 | fun someMethod(i:Int):Int = b.someMethod(i-1) + 1
45 | }
46 | val instance = Implementor(b)
47 |
--------------------------------------------------------------------------------
/050/src_chapt05_sect001_Expressions_Examples.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 05:
3 | //// Expressions: Operations on Data
4 | //// Section: 1. Expressions Examples
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | 4 * 5 // multiplication
10 | 3 + 7 // addition
11 | 6 - 1 // subtraction
12 | "a" + "b" // concatenation
13 | ( 1 + 2 ) // grouping
14 | -5 // negation
15 | a && b // boolean a AND b
16 | "Hello" // constant (String)
17 | 78 // another constant (Int)
18 | 3.14 // another constant (Double)
19 | 'A' // another constant (Char)
20 | arr[43] // index access
21 | funct(...) // function invocation
22 | Clazz() // instantiation
23 | Obj // singleton instance access
24 | q.a // dereferencing
25 | q.f() // another dereferencing
26 | if(){ } // language construct
27 | when(){ } // another language construct
28 |
--------------------------------------------------------------------------------
/050/src_chapt05_sect002_Expressions_Ubiquity.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 05:
3 | //// Expressions: Operations on Data
4 | //// Section: 2. Expressions Ubiquity
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | fun a() {
10 | }
11 |
12 | val aa = a()
13 |
--------------------------------------------------------------------------------
/050/src_chapt05_sect003_Numerical_Expressions.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 05:
3 | //// Expressions: Operations on Data
4 | //// Section: 3. Numerical Expressions
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | val l1:Long = 234567890L
10 | val i1:Int = 37
11 | val x = l1 / i1 // -> is a Long
12 |
13 | //----#### SNIPPET #### - 2
14 | val f1:Float = 2.45f
15 | val d1:Double = 37.6
16 | val x = f1 / d1 // -> is a Double
17 |
18 | //----#### SNIPPET #### - 3
19 | val i1:Int = 33
20 | val d1:Double = 37.6
21 | val x = i1 * d1 // -> is a Double
22 |
--------------------------------------------------------------------------------
/050/src_chapt05_sect004_Boolean_Expressions.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 05:
3 | //// Expressions: Operations on Data
4 | //// Section: 4. Boolean Expressions
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | val b1 = a == 7 && b == 3 || c == 4
10 | val b2 = a == 7 && (b == 3 || c == 4)
11 |
--------------------------------------------------------------------------------
/050/src_chapt05_sect007_Other_Operators.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 05:
3 | //// Expressions: Operations on Data
4 | //// Section: 7. Other Operators
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | val c:Int? = ... // an int or null
10 | val b = c!! // b is non-nullable!
11 | // the same: val b:Int = c!!
12 |
--------------------------------------------------------------------------------
/050/src_chapt05_sect008_Conversions.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 05:
3 | //// Expressions: Operations on Data
4 | //// Section: 8. Conversions
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | 7 + 10_000_000_000L -> Long
10 | 34 + 46.7 -> Double
11 |
12 | //----#### SNIPPET #### - 2
13 | "Number is " + 7.3 -> "Number is 7.3"
14 | "Number is " + 7.3.toString() -> "Number is 7.3"
15 | "Hell" + 'o' -> "Hello"
16 |
--------------------------------------------------------------------------------
/060/src_chapt06_sect003_Class_Comments.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 06:
3 | //// Comments in Kotlin Files
4 | //// Section: 3. Class Comments
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | /**
10 | * The comment ...
11 | * ...
12 | */
13 |
14 | //----#### SNIPPET #### - 2
15 | /**
16 | * The main activity class of the NumberGuess game app.
17 | * Extends from the
18 | * [android.support.v7.app.AppCompatActivity]
19 | * class and is thus compatible with earlier
20 | * Android versions.
21 | *
22 | * The app shows a GUI with the following buttons:
23 | * - **Start**: Starts the game
24 | * - **Do Guess**: Used for guessing a number
25 | *
26 | * Once started, the game secretly determines a random
27 | * number the user has to guess. The user performs
28 | * guesses and gets told if the guessed number is too
29 | * low, too high, or a hit.
30 | *
31 | * Once hit, the game is over.
32 | *
33 | * @see Constants
34 | *
35 | * @author Peter Späth
36 | * @since 1.0
37 | */
38 | class MainActivity : AppCompatActivity() {
39 | ...
40 | }
41 |
--------------------------------------------------------------------------------
/060/src_chapt06_sect004_Function_And_Property_Comments.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 06:
3 | //// Comments in Kotlin Files
4 | //// Section: 4. Function And Property Comments
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | ...
10 | class SomeClass {
11 | /**
12 | * This describes property prop
13 | * ...
14 | */
15 | val prop:Int = 7
16 |
17 | /**
18 | * This describes function func
19 | * ...
20 | */
21 | fun func() {
22 | ...
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/070/src_chapt07_sect001_Ifs_And_Whens.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 07:
3 | //// Structuralnewline Constructs
4 | //// Section: 1. Ifs And Whens
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | if( [condition] ) {
10 | [statements1]
11 | } else if( [condition2] ) {
12 | [statements2]
13 | } else if( [condition3] ) {
14 | [statements3]
15 | ... more "else ifs"
16 | } else {
17 | [statementsElse]
18 | }
19 |
20 | //----#### SNIPPET #### - 2
21 | if( v == 7 ) {
22 | abc1()
23 | } else {
24 | abc2()
25 | }
26 |
27 | //----#### SNIPPET #### - 3
28 | if( v == 7) abc1() else abc2()
29 |
30 | //----#### SNIPPET #### - 4
31 | val x = if( [condition] ) {
32 | [statements1]
33 | [value1]
34 | } else if( [condition2] ) {
35 | [statements2]
36 | [value2]
37 | } else if( [condition3] ) {
38 | [statements3]
39 | ... more "else ifs"
40 | } else {
41 | [statementsElse]
42 | [valueElse]
43 | }
44 |
45 | //----#### SNIPPET #### - 5
46 | val x = if( a > 3 ) 27 else 28
47 |
48 | //----#### SNIPPET #### - 6
49 | when( [expression] ) {
50 | val1 -> { ... }
51 | val2 -> { ... }
52 | ...
53 | else -> { ... }
54 | }
55 |
56 | //----#### SNIPPET #### - 7
57 | val x = when( [expression] ) {
58 | val1 -> { ... }
59 | val2 -> { ... }
60 | ...
61 | else -> { ... }
62 | }
63 |
64 | //----#### SNIPPET #### - 8
65 | when( [expression] ) {
66 | val1 -> { ... }
67 | val2,val3 -> { ... }
68 | ...
69 | else - > { ... }
70 | }
71 |
72 | //----#### SNIPPET #### - 9
73 | val x = when( [expression] ) {
74 | calc(val1) + 7 -> { ... }
75 | val2,val3 -> { ... }
76 | ...
77 | else -> { ... }
78 | }
79 |
80 | //----#### SNIPPET #### - 10
81 | val l = listOf(...)
82 | val x = when( [expression] ) {
83 | in l -> { ... }
84 | in 27..53 -> { ... }
85 | !in 100..110 -> { ... }
86 | ...
87 | else -> { ... }
88 | }
89 |
90 | //----#### SNIPPET #### - 11
91 | val q:Any = ... // any type
92 | val x = when(q) {
93 | is Int -> { ... }
94 | is String -> { ... }
95 | ...
96 | else -> { ... }
97 | }
98 |
99 | //----#### SNIPPET #### - 12
100 | val q = ... // some Int
101 | val x = when( q ){ 1 -> "Jean" 2 -> "Sam" else -> "" }
102 |
103 | //----#### SNIPPET #### - 13
104 | val x = when(val q = [some value]) {
105 | 1 -> q * 3
106 | 2 -> q * 4
107 | ...
108 | else -> 0
109 | }
110 |
--------------------------------------------------------------------------------
/070/src_chapt07_sect002_Ranges.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 07:
3 | //// Structuralnewline Constructs
4 | //// Section: 2. Ranges
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | val r1 = IntRange(1, 1000)
10 | val r2 = LongRange(1, 10_000_000_000)
11 | val r3 = CharRange('A', 'I')
12 |
13 | //----#### SNIPPET #### - 2
14 | val r1 = 1..1000
15 | val r2 = 1L..10_000_000_000L
16 | val r3 = 'A'..'I'
17 |
18 | //----#### SNIPPET #### - 3
19 | 1..1000 step 5
20 | (1..1000 step 5).reversed()
21 |
22 | //----#### SNIPPET #### - 4
23 | 1000 downTo 1 step 5
24 |
25 | //----#### SNIPPET #### - 5
26 | (1..1000 step 5).first // -> 1
27 | (1..1000 step 5).last // -> 996
28 | (1000 downTo 1 step 5).first // -> 1000
29 | (1000 downTo 1 step 5).last // -> 5
30 |
--------------------------------------------------------------------------------
/070/src_chapt07_sect003_For_And_While_Loops.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 07:
3 | //// Structuralnewline Constructs
4 | //// Section: 3. For And While Loops
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | for( i in [loop data] ) {
10 | // do something with i
11 | }
12 |
13 | //----#### SNIPPET #### - 2
14 | while( [condition] ) {
15 | // do something
16 | }
17 |
18 | do {
19 | // do something
20 | } while( [condition] )
21 |
22 | //----#### SNIPPET #### - 3
23 | while( [condition] ) {
24 | ...
25 | break // -> exit loop
26 | ...
27 | continue // -> next iteration
28 | ...
29 | }
30 |
--------------------------------------------------------------------------------
/070/src_chapt07_sect004_Scoping_Functions.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 07:
3 | //// Structuralnewline Constructs
4 | //// Section: 4. Scoping Functions
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | object.apply {
10 | ...
11 | }
12 |
13 | //----#### SNIPPET #### - 2
14 | class A { var x:Int, var y:Int }
15 | val instance = A()
16 | instance.x = 4
17 | instance.y = 5
18 | instance.y *= instance.x
19 |
20 | //----#### SNIPPET #### - 3
21 | class A { var x:Int, var y:Int }
22 | val instance = A().apply{
23 | this.x = 4
24 | this.y = 5
25 | this.y *= this.x
26 | }
27 |
28 | //----#### SNIPPET #### - 4
29 | class A { var x:Int, var y:Int }
30 | val instance = A().apply{
31 | x = 4
32 | y = 5
33 | y *= x
34 | }
35 |
36 | //----#### SNIPPET #### - 5
37 | var q = 37
38 | class A { var x:Int, var y:Int }
39 | val instance = A().apply {
40 | x = 4
41 | y = 5
42 | q = 44 // does not exist in A, so the q from
43 | // outside gets used
44 | }
45 |
46 | //----#### SNIPPET #### - 6
47 | val x = SomeClass().apply {
48 | // do things with the SomeClass instance
49 | // while assigning it to x
50 | }
51 |
52 | //----#### SNIPPET #### - 7
53 | class A {
54 | fun goA() { ... }
55 | ...
56 | val x = SomeClass().apply {
57 | this.x = ... // -> SomeClass.x
58 | x = ... // -> SomeClass.x
59 | this@A.goA() // -> A.goA()
60 | ...
61 | }
62 | }
63 |
64 | //----#### SNIPPET #### - 8
65 | object.let { o ->
66 | [statements] // do s.th. with 'o'
67 | [value]
68 | }
69 |
70 | //----#### SNIPPET #### - 9
71 | object.let {
72 | [statements] // do s.th. with 'it'
73 | [value]
74 | }
75 |
76 | //----#### SNIPPET #### - 10
77 | val s = "Hello World"
78 | val s2 = s.let { it + "\n" }
79 | // or s.let { string -> string + "\n" }
80 |
81 | //----#### SNIPPET #### - 11
82 | val o = ... // some value
83 | with(o){
84 | // o is now "this"
85 | ...
86 | }
87 |
88 | //----#### SNIPPET #### - 12
89 | with(object){
90 | f1(37)
91 | f1(12)
92 | fx("Hello")
93 | }
94 |
95 | //----#### SNIPPET #### - 13
96 | object.f1(37)
97 | object.f1(12)
98 | object.fx("Hello")
99 |
100 | //----#### SNIPPET #### - 14
101 | object.also { obj ->
102 | // 'obj' is object
103 | ...
104 | }
105 |
106 | //----#### SNIPPET #### - 15
107 | object.also {
108 | // 'it' is object
109 | ...
110 | }
111 |
112 | //----#### SNIPPET #### - 16
113 | val s = "Hello"
114 | val x = s.run {
115 | // 'this' is 's'
116 | ...
117 | [value]
118 | }
119 | // x now has [value]
120 |
121 | //----#### SNIPPET #### - 17
122 | var v:String? = ...
123 | ...
124 | if(v != null) {
125 | ...
126 | }
127 |
128 | //----#### SNIPPET #### - 18
129 | var v:String? = ...
130 | ...
131 | v?.run {
132 | ...
133 | }
134 |
--------------------------------------------------------------------------------
/070/src_chapt07_sect005_Conditional_Execution.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 07:
3 | //// Structuralnewline Constructs
4 | //// Section: 5. Conditional Execution
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | someInstance.takeIf { [boolean_expression] }?.run {
10 | // do something
11 | }
12 |
--------------------------------------------------------------------------------
/080/src_chapt08_sect001_Kotlin_And_Exceptions.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 08:
3 | //// Exceptions: Ifnewline Something Goesnewline Wrong
4 | //// Section: 1. Kotlin And Exceptions
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | try {
10 | // ... statements
11 | } catch(e:Exception) {
12 | // do something
13 | }
14 |
15 | //----#### SNIPPET #### - 2
16 | try {
17 | // ... statements
18 | } catch(e:Exception) {
19 | // do something...
20 | } finally {
21 | // do this by any means: ...
22 | }
23 |
24 | //----#### SNIPPET #### - 3
25 | import android.util.Log
26 | ...
27 | try {
28 | // ... statements
29 | } catch(e:Exception) {
30 | Log.e("LOG", "Some exception occurred", e)
31 | }
32 |
33 | //----#### SNIPPET #### - 4
34 | import android.util.Log
35 | ...
36 | try {
37 | // ... statements
38 | } catch(e:Exception) {
39 | Log.e("LOG", "Some exception occurred", e)
40 | Toast.makeText(this,"Error Code 36A",
41 | Toast.LENGTH_LONG).show()
42 | }
43 |
--------------------------------------------------------------------------------
/080/src_chapt08_sect002_More_Exceptions_Types.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 08:
3 | //// Exceptions: Ifnewline Something Goesnewline Wrong
4 | //// Section: 2. More Exceptions Types
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | try {
10 | // ... statements
11 | } catch(e:ExceptionType1) {
12 | // do something...
13 | } catch(e:ExceptionType2) {
14 | // do something...
15 | ... possibly more catch statements
16 | } finally {
17 | // do this by any means: ...
18 | }
19 |
20 | //----#### SNIPPET #### - 2
21 | try {
22 | // ... file access
23 | // ... array access
24 | } catch(e:IOException) {
25 | // do something...
26 | } catch(e:ArrayIndexOutOfBoundsException) {
27 | // do something...
28 | } catch(e:Exception) {
29 | // do something...
30 | } finally {
31 | // do this by any means: ...
32 | }
33 |
--------------------------------------------------------------------------------
/080/src_chapt08_sect003_Throwing_Exceptions_Yourself.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 08:
3 | //// Exceptions: Ifnewline Something Goesnewline Wrong
4 | //// Section: 3. Throwing Exceptions Yourself
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | throw exceptionInstance
10 |
11 | //----#### SNIPPET #### - 2
12 | val exc = Exception("The exception message")
13 | throw exc
14 |
15 | //----#### SNIPPET #### - 3
16 | throw Exception("The exception message")
17 |
18 | //----#### SNIPPET #### - 4
19 | class MyException(msg:String) : Exception(msg)
20 | ...
21 | try {
22 | ...
23 | throw MyException("an error occurred")
24 | ...
25 | } catch(e:MyException) {
26 | ...
27 | }
28 |
--------------------------------------------------------------------------------
/080/src_chapt08_sect004_Exceptions_in_Expressions.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 08:
3 | //// Exceptions: Ifnewline Something Goesnewline Wrong
4 | //// Section: 4. Exceptions in Expressions
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | val x = try{ arr[ind] }
10 | catch(e:ArrayIndexOutOfBoundsException) { -1 }
11 |
12 | //----#### SNIPPET #### - 2
13 | val v = map[someKey] ?:
14 | throw Exception("no such key in the map")
15 |
--------------------------------------------------------------------------------
/090/src_chapt09_sect001_Defining_And_Using_Arrays.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 09:
3 | //// Data Containers
4 | //// Section: 1. Defining And Using Arrays
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | Array
10 |
11 | //----#### SNIPPET #### - 2
12 | val someStringArray:Array = ...
13 | var someObjectArray:Array = ...
14 |
15 | //----#### SNIPPET #### - 3
16 | val byteArr:ByteArray = ...
17 | var intArr:IntArray = ...
18 | ...
19 |
--------------------------------------------------------------------------------
/090/src_chapt09_sect002_Array_Instantiation.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 09:
3 | //// Data Containers
4 | //// Section: 2. Array Instantiation
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | val byteArr:ByteArray = ByteArray(7)
10 | val shortArr:ShortArray = ShortArray(7)
11 | val intArr:IntArray = IntArray(7)
12 | val longArr:LongArray = LongArray(7)
13 | val doubleArr:DoubleArray = DoubleArray(7)
14 | val floatArr:FloatArray = FloatArray(7)
15 | val booleanArr:BooleanArray = BooleanArray(7)
16 |
17 | //----#### SNIPPET #### - 2
18 | { i ->
19 | [ program code ]
20 | [ expression ]
21 | }
22 |
23 | //----#### SNIPPET #### - 3
24 | { i -> (i+1) * (i+1) }
25 |
26 | //----#### SNIPPET #### - 4
27 | val arr = IntArray(10, { i -> (i+1) * (i+1) })
28 |
29 | //----#### SNIPPET #### - 5
30 | val objArr:Array =
31 | Array(7, { i -> ... })
32 |
33 | //----#### SNIPPET #### - 6
34 | val ages = IntArray(5)
35 | ages[0] = 26
36 | ages[1] = 56
37 | ages[2] = 12
38 | ages[3] = 17
39 | ages[4] = 26
40 |
41 | //----#### SNIPPET #### - 7
42 | val ages = intArrayOf(26, 56, 12, 17, 26)
43 |
44 | //----#### SNIPPET #### - 8
45 | val size = ...
46 | val arr:Array = arrayOfNulls(size)
47 |
48 | //----#### SNIPPET #### - 9
49 | val arr:Array = emptyArray()
50 |
--------------------------------------------------------------------------------
/090/src_chapt09_sect004_Sets__Lists_And_Maps.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 09:
3 | //// Data Containers
4 | //// Section: 4. Sets, Lists And Maps
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | Set
10 | List
11 | Map
12 |
13 | MutableSet
14 | MutableList
15 | MutableMap
16 |
17 | //----#### SNIPPET #### - 2
18 | val set1:Set = HashSet()
19 | val set2:MutableSet = HashSet()
20 |
21 | val set3 = setOf(4, 7, 55)
22 | val set4 = setOf(4, 7, 55)
23 | val set5 = mutableSetOf(4, 7, 55)
24 |
25 | //----#### SNIPPET #### - 3
26 | setOf(1, 2, 3) + setOf(2, 3, 4) // -> [1, 2, 3, 4]
27 | setOf(1, 2, 3, 4) + 5 // -> [1, 2, 3, 4, 5]
28 | setOf(1, 2, 3) - setOf(3, 4) // -> [1, 2]
29 | setOf(1, 2, 3) - 2 // -> [1, 3]
30 |
31 | //----#### SNIPPET #### - 4
32 | val list1:List = ArrayList()
33 | val list2:MutableList = ArrayList()
34 |
35 | val list3 = listOf(4, 7, 55)
36 | val list4 = listOf(4, 7, 55)
37 | val list5 = mutableListOf(4, 7, 55)
38 |
39 | //----#### SNIPPET #### - 5
40 | val array = arrayOf(...)
41 | val list = array.toList()
42 |
43 | //----#### SNIPPET #### - 6
44 | listOf(1, 2, 3) + listOf(2, 3) // -> [1, 2, 3, 2, 3]
45 | listOf(1, 2, 3, 4) + 5 // -> [1, 2, 3, 4, 5]
46 |
47 | //----#### SNIPPET #### - 7
48 | val map1:Map = ...
49 | var map2:Map = ...
50 | val map3:MutableMap = ...
51 |
52 | //----#### SNIPPET #### - 8
53 | val map: MutableMap =
54 | HashMap().apply {
55 | this[152835937] = "Albert Einstein"
56 | this[273495357] = "John Smith"
57 | this[346068589] = "John Smith"
58 | this[484767775] = "Barbra Streisand"
59 | }
60 |
61 | //----#### SNIPPET #### - 9
62 | val map = mutableMapOf(
63 | 152835937 to "Albert Einstein",
64 | 273495357 to "John Smith",
65 | 346068589 to "John Smith",
66 | 484767775 to "Barbra Streisand"
67 | )
68 | val map2 = mapOf(
69 | 152835937 to "Albert Einstein",
70 | ... )
71 |
--------------------------------------------------------------------------------
/090/src_chapt09_sect005_Pairs_and_Triples.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 09:
3 | //// Data Containers
4 | //// Section: 5. Pairs and Triples
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | val pair = Pair(
10 | firstVal, secondVal)
11 | val triple = Triple(
12 | firstVal, secondVal, thirdVal)
13 |
14 | //----#### SNIPPET #### - 2
15 | val pair = Pair("Earth", 12800.0)
16 |
--------------------------------------------------------------------------------
/090/src_chapt09_sect006_Loops_Over_Data_Containers.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 09:
3 | //// Data Containers
4 | //// Section: 6. Loops Over Data Containers
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | val container = ... // array or set or list
10 | container.forEach { elem ->
11 | // do something with elem
12 | }
13 |
14 | //----#### SNIPPET #### - 2
15 | val container = listOf(1, 2, 3, 4, -1)
16 | container.forEach { elem ->
17 | Log.d("LOG", elem.toString())
18 | }
19 |
20 | //----#### SNIPPET #### - 3
21 | var index = 0
22 | container.forEach { elem ->
23 | // ... do s.th. with elem
24 | index++ // NOT ALLOWED!
25 | }
26 |
27 | //----#### SNIPPET #### - 4
28 | container.forEachIndexed { index, elem ->
29 | // ... do s.th. with elem
30 | }
31 |
--------------------------------------------------------------------------------
/090/src_chapt09_sect008_Grouping__Folding__Reducing_And_Zipping.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 09:
3 | //// Data Containers
4 | //// Section: 8. Grouping, Folding, Reducing And Zipping
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | data class Car(id:Int,make:Int,name:String,vin:String)
10 | val cars = listOf(
11 | Car(1, 1994, "Sirus", "WXX 130 007-1J-582943"),
12 | Car(2, 1997, "Sirus", "WXX 130 008-1J-582957"),
13 | Car(3, 2010, "Casto 4.0", "WXQ 456 088-4K-005614"),
14 | Car(4, 2010, "Babo MX", "WYY 518 004-55-171598"),
15 | Car(5, 1994, "Casto 4.0", "WXQ 456 005-4K-005658"),
16 | Car(6, 2011, "Quasto", "WA0 100 036-00-012378")
17 | )
18 |
19 | //----#### SNIPPET #### - 2
20 | data class Car(id:Int,make:Int,name:String,vin:String)
21 | val cars = listOf( ... )
22 | val groupedByMake = cars.groupBy(Car::make)
23 | ...
24 | val group1997:List = groupedByMake[1997]
25 |
26 | //----#### SNIPPET #### - 3
27 | val groupedByMake = cars.groupBy { car -> car.make }
28 |
29 | //----#### SNIPPET #### - 4
30 | val someObject = ...
31 | list.forEach { elem ->
32 | // update someObj using elem
33 | ...
34 | }
35 |
36 | //----#### SNIPPET #### - 5
37 | array.zip(otherArray)
38 | -or- array zip otherArray
39 | array.zip(list)
40 | -or- array zip list
41 | collection.zip(array)
42 | -or- collection zip array
43 | collection.zip(otherCollection)
44 | -or- collection zip otherCollection
45 |
46 | //----#### SNIPPET #### - 6
47 | val fruits = listOf("Bananas", "apples", "Oranges")
48 | val prices = listOf(1.69, 2.19, 2.79)
49 | val fruitsAndPrices = fruits zip prices
50 | // or fruits.zip(prices)
51 | ...
52 | fruitsAndPrices.forEach { p ->
53 | // p = Pair("Bananas", 1.69) aso.
54 | }
55 |
--------------------------------------------------------------------------------
/090/src_chapt09_sect010_The_Spread_Operator.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 09:
3 | //// Data Containers
4 | //// Section: 10. The Spread Operator
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | function xyz(a:Int, vararg x:String) {
10 | ...
11 | }
12 |
13 | val arr = arrayOf("1", "2", "3", "4", "5")
14 | xyz(42, *arr)
15 |
--------------------------------------------------------------------------------
/090/src_chapt09_sect012_A_Statistics_Class_For_The_NumberGuess_App.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 09:
3 | //// Data Containers
4 | //// Section: 12. A Statistics Class For The NumberGuess App
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 |
12 |
13 | //----#### SNIPPET #### - 2
14 |
15 | ...
16 |
20 |
22 |
24 |
25 |
26 | //----#### SNIPPET #### - 3
27 |
28 |
36 |
37 |
41 |
48 |
49 |
50 |
51 |
52 |
53 | //----#### SNIPPET #### - 4
54 |
55 |
72 |
73 |
80 |
81 |
86 |
87 |
93 |
94 |
96 |
97 |
101 |
105 |
112 |
118 |
119 |
120 |
122 |
123 |
130 |
131 |
133 |
134 |
138 |
142 |
143 |
144 |
145 |
146 | //----#### SNIPPET #### - 5
147 | import kotlinx.android.synthetic.main.activity_main.*
148 | import kotlinx.android.synthetic.main.content_main.*
149 |
150 | //----#### SNIPPET #### - 6
151 | override fun onCreate(savedInstanceState: Bundle?) {
152 | super.onCreate(savedInstanceState)
153 | setContentView(R.layout.activity_main)
154 | setSupportActionBar(toolbar) // NEW
155 |
156 | fetchSavedInstanceData(savedInstanceState)
157 | doGuess.setEnabled(started)
158 | }
159 |
160 | //----#### SNIPPET #### - 7
161 |
162 |
173 |
174 | //----#### SNIPPET #### - 8
175 |
176 | Statistics
177 |
178 | //----#### SNIPPET #### - 9
179 | override
180 | fun onCreateOptionsMenu(menu: Menu): Boolean {
181 | val inflater: MenuInflater = menuInflater
182 | inflater.inflate(R.menu.menu_options, menu)
183 | return true
184 | }
185 |
186 | private fun openStatistics() {
187 | val intent: Intent = Intent(this,
188 | StatisticsActivity::class.java)
189 | startActivity(intent)
190 | }
191 |
192 | //----#### SNIPPET #### - 10
193 |
194 |
206 |
207 |
208 | //----#### SNIPPET #### - 11
209 |
210 | package kotlinforandroid.book.numberguess
211 |
212 | import android.support.v7.app.AppCompatActivity
213 | import android.os.Bundle
214 | import android.view.ViewGroup
215 | import android.widget.TextView
216 | import kotlinforandroid.book.numberguess.
217 | statistics.Statistics
218 |
219 | class StatisticsActivity : AppCompatActivity() {
220 |
221 | override
222 | fun onCreate(savedInstanceState: Bundle?) {
223 | super.onCreate(savedInstanceState)
224 | setContentView(R.layout.activity_statistics)
225 |
226 | showData(Statistics.getStatistics())
227 | }
228 |
229 | fun showData(s:List) {
230 | val container = findViewById(
231 | R.id.statisticsContainer)
232 | container.removeAllViews()
233 | s.forEach {line ->
234 | container.addView(TextView(this).apply {
235 | text = line
236 | })
237 | }
238 | }
239 | }
240 |
241 | //----#### SNIPPET #### - 12
242 | package kotlinforandroid.book.numberguess.statistics
243 |
244 | object Statistics {
245 | fun getStatistics(): List {
246 | return emptyList()
247 | }
248 | }
249 |
250 | //----#### SNIPPET #### - 13
251 | package kotlinforandroid.book.numberguess.statistics
252 |
253 | object Statistics {
254 | data class GameSessionRecord(val numberToGuess:Int,
255 | val tries:Int) : Serializable
256 | val data: ArrayList = ArrayList()
257 |
258 | fun getStatistics(): List {
259 | return emptyList()
260 | }
261 | }
262 |
263 | //----#### SNIPPET #### - 14
264 | override
265 | fun onCreate(savedInstanceState: Bundle?) {
266 | super.onCreate(savedInstanceState)
267 | setContentView(R.layout.activity_statistics)
268 |
269 | restoreData(savedInstanceState) // new!
270 | showData(Statistics.getStatistics())
271 | }
272 |
273 | //----#### SNIPPET #### - 15
274 | fun restoreData(savedInstanceState: Bundle?) {
275 | savedInstanceState?.run {
276 | getSerializable("statistics.data")?.run {
277 | Statistics.data.clear()
278 | Statistics.data.addAll( this as
279 | ArrayList)
280 | }
281 | }
282 | }
283 |
284 | override fun onSaveInstanceState(outState: Bundle?) {
285 | super.onSaveInstanceState(outState)
286 | outState?.putSerializable("statistics.data",
287 | Statistics.data)
288 | }
289 |
290 | //----#### SNIPPET #### - 16
291 | object Statistics {
292 | ...
293 | fun register(numberToGuess:Int, tries:Int) {
294 | data.add(GameSessionRecord(numberToGuess,
295 | tries))
296 | }
297 | }
298 |
299 | //----#### SNIPPET #### - 17
300 | fun guess(v:View) {
301 | ...
302 | if (g < number) {
303 | ...
304 | } else if (g > number) {
305 | ...
306 | } else {
307 | Statistics.register(number, tries)
308 | ...
309 | }
310 | ...
311 | }
312 |
313 | //----#### SNIPPET #### - 18
314 | private fun numberOfSessions() : Int =
315 | data.size
316 |
317 | //----#### SNIPPET #### - 19
318 | private fun averageTriesNeeded() : Double =
319 | if(data.size > 0) data.map { rec -> rec.tries }
320 | .sum().toDouble() / data.size ;
321 | else 0.0
322 |
323 | //----#### SNIPPET #### - 20
324 | private fun triesNeededStdDev() : Double {
325 | if(data.size < 2) return 0.0
326 | val avg = averageTriesNeeded()
327 | return Math.sqrt(
328 | data.map {
329 | rec -> Math.pow(rec.tries - avg, 2.0)
330 | }.sum() / (data.size - 1))
331 | }
332 |
333 | //----#### SNIPPET #### - 21
334 | private fun neededTriesDistrib() : Map =
335 | data.groupBy({rec -> rec.tries}).
336 | mapValues { me -> me.value.size }
337 |
338 | //----#### SNIPPET #### - 22
339 | private
340 | fun triesByNumberToGuess() : Map =
341 | data.groupBy({rec -> rec.numberToGuess})
342 | .mapValues { me ->
343 | me.value.map{it.tries}.sum().toDouble()
344 | / me.value.size }
345 |
346 | //----#### SNIPPET #### - 23
347 | fun getStatistics(): List {
348 | val twoDigits = DecimalFormat().
349 | apply{ maximumFractionDigits = 2 }
350 | val triesDistrib = neededTriesDistrib().
351 | toSortedMap().toString()
352 | val triesByNumber = triesByNumberToGuess().
353 | toSortedMap().mapValues {
354 | me -> twoDigits.format(me.value) }
355 | .toString()
356 | return listOf(
357 | "Sessions: ${numberOfSessions()}",
358 | "Average Tries: ${averageTriesNeeded()}",
359 | "Tries Standard Dev: ${triesNeededStdDev()}",
360 | "Tries Distrib: ${triesDistrib}",
361 | "Tries by Number: ${triesByNumber}"
362 | )
363 | }
364 |
--------------------------------------------------------------------------------
/100/src_chapt10_sect001_What_NULL_is.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 10:
3 | //// True, False Andnewline Undecided:newline Nullability
4 | //// Section: 1. What NULL is
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | val b:Boolean = ... // some condition
10 | if(b) {
11 | ... // do something
12 | } else {
13 | ... // do something else
14 | }
15 |
16 | //----#### SNIPPET #### - 2
17 | val instance = ... // some object
18 | val b:Boolean = ... // some condition
19 | if(instance == null) {
20 | ... // do something
21 | } else if(b) {
22 | ... // do something else
23 | } else {
24 | ... // do something else
25 | }
26 |
27 | //----#### SNIPPET #### - 3
28 | val b:Boolean = ... // some three-valued condition
29 | ifundecided(b) {
30 | ... // do something
31 | } if(b) {
32 | ... // do something else
33 | } else {
34 | ... // do something else
35 | }
36 |
--------------------------------------------------------------------------------
/100/src_chapt10_sect002_How_Nullability_Gets_Handled_Inside_Kotlin.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 10:
3 | //// True, False Andnewline Undecided:newline Nullability
4 | //// Section: 2. How Nullability Gets Handled Inside Kotlin
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | var p:SomeType = ...
10 | ...
11 | p = null
12 |
13 | //----#### SNIPPET #### - 2
14 | class A(var p:SomeType) ...
15 | A(null) // does not compile
16 |
17 | fun f(p:SomeType) { ... }
18 | f(null) // does not compile
19 |
20 | //----#### SNIPPET #### - 3
21 | var p:SomeType? = ...
22 | p = null // OK
23 |
24 | class A(var p:SomeType?) ...
25 | A(null) // OK
26 |
27 | fun f(p:SomeType?) { ... }
28 | f(null) // OK
29 |
30 | //----#### SNIPPET #### - 4
31 | var p:SomeType? = ...
32 | ...
33 | p.property // does not compile
34 | p.function() // does not compile
35 |
36 | //----#### SNIPPET #### - 5
37 | var p:SomeType? = ...
38 | ...
39 | p?.property // OK
40 | p?.function() // OK
41 |
42 | //----#### SNIPPET #### - 6
43 | var p:SomeType? = null
44 |
45 | val res:TypeOfProperty? = p?.property // -> null
46 |
47 | val res2:TypeOfFunct? = p?.function() // -> null
48 | // ... and function() not invoked
49 |
50 | //----#### SNIPPET #### - 7
51 | var p:String? = "Hello"
52 | var s1 = p?:"default" // -> "Hello"
53 | p = null
54 | var s2 = p?:"default" // -> "default"
55 |
56 | //----#### SNIPPET #### - 8
57 | var p:String? = ...
58 | // for whatever reason we know that p cannot be null
59 |
60 | val len = p!!.length
61 | // valid, because the !! tells it cannot be null
62 | // If it accidentally _is_ null, we'll crash here.
63 |
64 | //----#### SNIPPET #### - 9
65 | var p:String? = ...
66 |
67 | val len = p!!.length
68 | val intVal = p.toInt()
69 |
--------------------------------------------------------------------------------
/110/src_chapt11_sect001_Identity_in_Kotlin.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 11:
3 | //// Handling Equality
4 | //// Section: 1. Identity in Kotlin
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | data class A(val x:Double)
10 | val a = A(7.0)
11 | val b = A(7.0)
12 | val c = a
13 | val aIdenticalToC = a === c // -> true
14 | val aIdenticalToB = a === b // -> false
15 |
--------------------------------------------------------------------------------
/110/src_chapt11_sect003_Equals_and_Hash_Code.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 11:
3 | //// Handling Equality
4 | //// Section: 3. Equals and Hash Code
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | class A(val v:Int) {
10 | override fun hashCode():Int {
11 | return ...
12 | }
13 | override fun equals(other:Any?):Boolean {
14 | return ...
15 | }
16 | }
17 |
18 | val m = mapOf(A(7) to 8, A(8) to 9)
19 |
20 | //----#### SNIPPET #### - 2
21 | val searchKey:A = ...
22 | m[searchKey]
23 |
24 | //----#### SNIPPET #### - 3
25 | class Person(val lastName:String,
26 | val firstName:String,
27 | val birthday:String,
28 | val gender:Char)
29 |
30 | //----#### SNIPPET #### - 4
31 | class Person(val lastName:String,
32 | val firstName:String,
33 | val birthday:String,
34 | val gender:Char) {
35 | override fun equals(other:Any?):Boolean {
36 | if(other == null) return false
37 | if(other !is Person) return false
38 | if(lastName != other.lastName) return false
39 | if(firstName != other.firstName) return false
40 | if(birthday != other.birthday) return false
41 | if(gender != other.gender) return false
42 | return true
43 | }
44 | }
45 |
46 | //----#### SNIPPET #### - 5
47 | class Person(val lastName:String,
48 | val firstName:String,
49 | val birthday:String,
50 | val gender:Char) {
51 | override fun equals(other:Any?):Boolean {
52 | if(other == null) return false
53 | if(other !is Person) return false
54 | if(lastName != other.lastName) return false
55 | if(firstName != other.firstName) return false
56 | if(birthday != other.birthday) return false
57 | if(gender != other.gender) return false
58 | return true
59 | }
60 |
61 | override fun hashCode(): Int {
62 | return Objects.hash(super.hashCode(),
63 | lastName, firstName, birthday, gender)
64 | }
65 | }
66 |
67 | //----#### SNIPPET #### - 6
68 | data class Person(val lastName:String,
69 | val firstName:String,
70 | val birthday:String,
71 | val gender:Char)
72 |
--------------------------------------------------------------------------------
/120/src_chapt12_sect001_Kotlin_And_Functional_Programming.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 12:
3 | //// Back to Math:newline Functionalnewline Programming
4 | //// Section: 1. Kotlin And Functional Programming
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | ([parameters]) -> [result-type]
10 |
11 | //----#### SNIPPET #### - 2
12 | val f : (Int,String) -> String = ...
13 |
14 | //----#### SNIPPET #### - 3
15 | val f1 = { -> Log.d("LOG", "Hello Kotlin") }
16 | val f2 = { i:Int, s:String -> "${i}: ${s}" }
17 | ...
18 | fun ff(fun1: (Int,String) -> String):String {
19 | return fun1(7, "Hello")
20 | }
21 | ff(f2)
22 | ff( { i:Int,s:String -> "${i}- ${s}" } )
23 |
24 | //----#### SNIPPET #### - 4
25 | val f = { i:Int, s:String ->
26 | i.toString() + ": " + s }
27 | fun fun1(p: (Int,String) -> String) {
28 | p(42, "Hello")
29 | }
30 | fun1 { i:Int, s:String -> i.toString() + ": " + s }
31 |
32 | //----#### SNIPPET #### - 5
33 | object X {
34 | fun add(a:Int, b:Int): Int = a + b
35 | }
36 | ...
37 | val f : (Int,Int) -> Int = X::add
38 |
39 | //----#### SNIPPET #### - 6
40 | class X {
41 | fun add(a:Int, b:Int): Int = a + b
42 | }
43 | ...
44 | val f : X.(Int,Int) -> Int = X::add
45 |
46 | //----#### SNIPPET #### - 7
47 | class X {
48 | fun add(a:Int, b:Int): Int = a + b
49 | }
50 | ...
51 | val x1 = X()
52 | val f : (Int,Int) -> Int = x1::add
53 |
--------------------------------------------------------------------------------
/120/src_chapt12_sect002_Functions_Without_Names__Lambda_Functions.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 12:
3 | //// Back to Math:newline Functionalnewline Programming
4 | //// Section: 2. Functions Without Names: Lambda Functions
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | fun functionName([parameters]): ReturnType {
10 | ...
11 | }
12 |
13 | //----#### SNIPPET #### - 2
14 | fun functionName([parameters]): ReturnType = ...
15 |
16 | //----#### SNIPPET #### - 3
17 | val varName = 37
18 |
19 | //----#### SNIPPET #### - 4
20 | val f = { i:Int, s:String ->
21 | i.toString() + ": " + s }
22 |
23 | //----#### SNIPPET #### - 5
24 | ff( { i:Int,s:String -> "${i}- ${s}" } )
25 |
26 | //----#### SNIPPET #### - 6
27 | [lambda_function].invoke([parameters])
28 | [lambda_function]([parameters])
29 |
30 | //----#### SNIPPET #### - 7
31 | val f = { i:Int, s:String ->
32 | i.toString() + ": " + s }
33 |
34 | //----#### SNIPPET #### - 8
35 | { par ->
36 | ... // do something with 'par' }
37 | {
38 | ... // do something with 'it' }
39 |
40 | //----#### SNIPPET #### - 9
41 | val f : (String, Int) -> String = { s:String, _ ->
42 | // the Int parameter is not used
43 | s + "!"
44 | }
45 |
--------------------------------------------------------------------------------
/120/src_chapt12_sect003_Loops_Once_Again.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 12:
3 | //// Back to Math:newline Functionalnewline Programming
4 | //// Section: 3. Loops Once Again
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | val arr = arrayOf("Joe", "Isabel", "John" }
10 | arr.forEach { name ->
11 | Log.d("A name: ${name}")
12 | }
13 | arr.forEachIndexed { i,s ->
14 | Log.d("Name #${i}: ${name}")
15 | }
16 |
17 | //----#### SNIPPET #### - 2
18 | public inline fun Array.forEach(
19 | action: (T) -> Unit): Unit {
20 | for (element in this) action(element)
21 | }
22 |
23 | //----#### SNIPPET #### - 3
24 | originalCollection.
25 | filter([filter_function]).
26 | map([mapping_function]).
27 | take(37).
28 | forEach { elem ->
29 | ...
30 | }
31 |
--------------------------------------------------------------------------------
/120/src_chapt12_sect004_Functions_With_Receivers.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 12:
3 | //// Back to Math:newline Functionalnewline Programming
4 | //// Section: 4. Functions With Receivers
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | val f : ReceiverType.([parameters]) = ...
10 |
11 | //----#### SNIPPET #### - 2
12 | class A {
13 | var d:Double = 0.0
14 | fun plus(x:Double) = d + x
15 | }
16 | val f : A.(Double) -> Double =
17 | { x:Double -> this.d - x }
18 | fun A.minus(x:Double) = f
19 |
20 | //----#### SNIPPET #### - 3
21 | class X {
22 | fun add(a:Int, b:Int): Int = a + b
23 | }
24 | ...
25 | val f : X.(Int,Int) -> Int = X::add
26 |
--------------------------------------------------------------------------------
/120/src_chapt12_sect005_Inline_Functions.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 12:
3 | //// Back to Math:newline Functionalnewline Programming
4 | //// Section: 5. Inline Functions
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | class A {
10 | fun function1(i:Int, f:(Int) -> String): String {
11 | return f(i)
12 | }
13 | fun function2() {
14 | val a = 7
15 | val s = function1(8) {
16 | i -> "8 + a = " + (i+a) }
17 | }
18 | }
19 |
20 | //----#### SNIPPET #### - 2
21 | public class A {
22 | public String function1(int i,
23 | Function1 super Integer, String> f) {
24 | return f.invoke(i);
25 | }
26 |
27 | public void function2() {
28 | int a = 7;
29 | String s2 = this.function1(8,
30 | new Function1(a){
31 | final int $a;
32 | public String invoke(int i) {
33 | return "8 + a = " + (i + this.$a);
34 | }
35 | {
36 | this.$a = n;
37 | super(1);
38 | }
39 | });
40 | }
41 | }
42 |
43 | //----#### SNIPPET #### - 3
44 | class A {
45 | inline fun function1(i:Int, f:(Int) -> String): String {
46 | return f(i)
47 | }
48 | fun function2() {
49 | val a = 7
50 | val s = function1(8) {
51 | i -> "8 + a = " + (i+a) }
52 | }
53 | }
54 |
55 | //----#### SNIPPET #### - 4
56 | public class A {
57 | public String function1(int i,
58 | Function1 super Integer, String> f) {
59 | return f.invoke(i);
60 | }
61 |
62 | public void function2() {
63 | int a = 7;
64 | int i$iv;
65 | int i = i$iv = 8;
66 | String s2 = "8 + a = " + (i + a);
67 | }
68 | }
69 |
70 | //----#### SNIPPET #### - 5
71 | int i$iv;
72 | int i = i$iv = 8;
73 | String s2 = "8 + a = " + (i + a);
74 |
--------------------------------------------------------------------------------
/120/src_chapt12_sect006_Filters.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 12:
3 | //// Back to Math:newline Functionalnewline Programming
4 | //// Section: 6. Filters
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | data class Employee(val firstName:String,
10 | val lastName:String,
11 | val ssn:String,
12 | val yearHired:Int)
13 | val employees = listOf(
14 | Employee("John", "Smith", "123-12-0001",
15 | 1987),
16 | Employee("Linda", "Thundergaard", "123-12-0002",
17 | 1987),
18 | Employee("Lewis", "Black", "123-12-0003",
19 | 1977),
20 | Employee("Evans", "Brightsmith", "123-12-0004",
21 | 1991)
22 | )
23 | val before1990 = mutableListOf()
24 | for(empl in employees) {
25 | if(empl.yearHired < 1990) before1990.add(empl)
26 | }
27 | ... // do something with before1990
28 |
29 | //----#### SNIPPET #### - 2
30 | data class Employee(val firstName:String,
31 | val lastName:String,
32 | val ssn:String,
33 | val yearHired:Int)
34 | val employees = listOf(
35 | Employee("John", "Smith", "123-12-0001",
36 | 1987),
37 | Employee("Linda", "Thundergaard", "123-12-0002",
38 | 1987),
39 | Employee("Lewis", "Black", "123-12-0003",
40 | 1977),
41 | Employee("Evans", "Brightsmith", "123-12-0004",
42 | 1991)
43 | )
44 | val before1990 = employees.filter {
45 | it.yearHired < 1990 }.toList()
46 | ... // do something with before1990
47 |
--------------------------------------------------------------------------------
/130/src_chapt13_sect000_.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 13:
3 | //// About Type Safety: Generics
4 | //// Section: 0.
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | class AdderInt {
10 | fun add(i:Int) {
11 | ...
12 | }
13 | }
14 |
15 | //----#### SNIPPET #### - 2
16 | class AdderString {
17 | fun add(s:String) {
18 | ...
19 | }
20 | }
21 |
22 | //----#### SNIPPET #### - 3
23 | class Adder {
24 | fun add(toAdd:T) {
25 | ...
26 | }
27 | }
28 |
29 | //----#### SNIPPET #### - 4
30 | class Adder {
31 | fun add(toAdd:T) {
32 | ...
33 | }
34 | }
35 | val intAdder = Adder()
36 | val stringAdder = Adder()
37 |
38 | //----#### SNIPPET #### - 5
39 | class Adder {
40 | fun add(toAdd:T) {
41 | ...
42 | }
43 | }
44 | val intAdder:Adder = Adder()
45 | val stringAdder:Adder = Adder()
46 |
47 | //----#### SNIPPET #### - 6
48 | val p1 = Pair("A", "B")
49 | val p2 = Pair(1, "A")
50 |
51 | //----#### SNIPPET #### - 7
52 | val l1: List = listOf("A","B","C")
53 | val l2: MutableList = mutableListOf(1, 2, 3)
54 |
--------------------------------------------------------------------------------
/130/src_chapt13_sect001_Simple_Generics.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 13:
3 | //// About Type Safety: Generics
4 | //// Section: 1. Simple Generics
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | class TheClass<[type-list]> {
10 | [class-body]
11 | }
12 | interface TheInterface<[type-list]> {
13 | [interface-body]
14 | }
15 |
16 | //----#### SNIPPET #### - 2
17 | class TheClass(val p1: A, val p2: B?) {
18 | constructor(p1:A) : this(p1, null)
19 | init {
20 | var x:A = p1
21 | ...
22 | }
23 | fun function(p: A) : B? = p2
24 | }
25 |
--------------------------------------------------------------------------------
/130/src_chapt13_sect002_Declaration_Side_Variance.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 13:
3 | //// About Type Safety: Generics
4 | //// Section: 2. Declaration-Side Variance
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | class A { ... }
10 | var a = A()
11 | var b = A()
12 |
13 | a = b // variance?
14 | ... or ...
15 | b = a // variance?
16 |
17 | //----#### SNIPPET #### - 2
18 | class A {
19 | fun add(p:T) { ... }
20 | }
21 | var a = A()
22 | var b = A()
23 |
24 | b = a // variance?
25 | b.add(37)
26 |
27 | //----#### SNIPPET #### - 3
28 | class A {
29 | fun extract(): T = ...
30 | }
31 | var a = A()
32 | var b = A()
33 |
34 | a = b // variance?
35 | val extracted:String = a.extract()
36 |
37 | //----#### SNIPPET #### - 4
38 | class A {
39 | fun extract(): T = ...
40 | }
41 | var a = A()
42 | var b = A()
43 |
44 | b = a // variance?
45 | val extracted:String = b.extract()
46 |
47 | //----#### SNIPPET #### - 5
48 | class A {
49 | fun add(p:T) { ... }
50 | }
51 | var a = A()
52 | var b = A()
53 |
54 | a = b // variance?
55 | a.add("World")
56 |
57 | //----#### SNIPPET #### - 6
58 | class A {
59 | fun extract(): T = ...
60 | }
61 | var a = A()
62 | var b = A()
63 |
64 | b = a // variance? YES!
65 | val extracted:String = b.extract()
66 | // OK, because we are reading!
67 |
68 | //----#### SNIPPET #### - 7
69 | class A {
70 | fun add(p:T) { ... }
71 | }
72 | var a = A()
73 | var b = A()
74 |
75 | a = b // variance? YES!
76 | b.add("World")
77 | // OK, because we are writing!
78 |
--------------------------------------------------------------------------------
/130/src_chapt13_sect003_Variance_For_Immutable_Collections.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 13:
3 | //// About Type Safety: Generics
4 | //// Section: 3. Variance For Immutable Collections
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | val coll1 = listOf("A", "B") // immutable
10 | val coll2:List = coll1 // allowed!
11 |
--------------------------------------------------------------------------------
/130/src_chapt13_sect004_Type_Projections.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 13:
3 | //// About Type Safety: Generics
4 | //// Section: 4. Type Projections
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | class Producer {
10 | fun getData(): Iterable? = null
11 | }
12 | class Consumer {
13 | fun setData(p:Iterable) { }
14 | }
15 |
16 | class A {
17 | fun add(p:Producer) { }
18 | fun extractTo(p:Consumer) { }
19 | }
20 |
21 | //----#### SNIPPET #### - 2
22 | var a = A()
23 | var b = A()
24 |
25 | var inputStrings = Producer()
26 | var inputAny = Producer()
27 | a.add(inputStrings)
28 | a.add(inputAny) // FAILS!
29 | b.add(inputStrings) // only because o "out"
30 | b.add(inputAny)
31 |
32 | var outputAny = Consumer()
33 | var outputStrings = Consumer()
34 | a.extractTo(outputAny) // only because of "in"
35 | a.extractTo(outputStrings)
36 | b.extractTo(outputAny)
37 | b.extractTo(outputStrings) // FAILS!
38 |
--------------------------------------------------------------------------------
/130/src_chapt13_sect005_Star_Projections.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 13:
3 | //// About Type Safety: Generics
4 | //// Section: 5. Star Projections
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | interface Interf {
10 | ...
11 | }
12 |
13 | val x:Interf<*, Int> = ...
14 | // ... same as Interf
15 |
16 | val y:Interf = ...
17 | // ... same as Interf
18 |
--------------------------------------------------------------------------------
/130/src_chapt13_sect006_Generic_Functions.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 13:
3 | //// About Type Safety: Generics
4 | //// Section: 6. Generic Functions
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | fun fun1(par1:A, par2:Int) {
10 | ...
11 | }
12 |
13 | fun fun2(par1:A, par2:B) {
14 | ...
15 | }
16 |
17 | fun fun3(par1:String) : A {
18 | ...
19 | }
20 |
21 | fun fun4(par1:String) : List {
22 | ...
23 | }
24 |
25 | //----#### SNIPPET #### - 2
26 | fun1("Hello", 37)
27 |
28 | fun2(37, "World")
29 |
30 | val s:String = fun3("A")
31 |
--------------------------------------------------------------------------------
/130/src_chapt13_sect007_Generic_Constraints.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 13:
3 | //// About Type Safety: Generics
4 | //// Section: 7. Generic Constraints
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 |
10 |
11 | //----#### SNIPPET #### - 2
12 | class { ... }
13 |
14 | //----#### SNIPPET #### - 3
15 | class Adder {
16 | var v:Double = 0.0
17 | fun add(value:T) {
18 | v += value.toDouble()
19 | }
20 | }
21 |
22 | //----#### SNIPPET #### - 4
23 | class Adder {
24 | var v:Double = 0.0
25 | fun add(value:T) {
26 | // T is a Number, so it _has_ a toDouble()
27 | v += value.toDouble()
28 | }
29 | }
30 |
31 | //----#### SNIPPET #### - 5
32 | class Adder {
33 | var v:Double = 0.0
34 | fun add(value:T) {
35 | v += value.toDouble()
36 | }
37 | }
38 |
39 | //----#### SNIPPET #### - 6
40 | val adder = Adder()
41 | adder.add(37)
42 | adder.add(3.14)
43 | adder.add(1.0f)
44 |
45 | //----#### SNIPPET #### - 7
46 | class TheClass where T : UpperBound1,
47 | T : UpperBound2, ...
48 | {
49 | ...
50 | }
51 |
52 | //----#### SNIPPET #### - 8
53 | fun functionName(...) where T : UpperBound1,
54 | T : UpperBound2, ...
55 | {
56 | ...
57 | }
58 |
59 | //----#### SNIPPET #### - 9
60 | class TheClass > {
61 | ...
62 | }
63 |
--------------------------------------------------------------------------------
/140/src_chapt14_sect000_.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 14:
3 | //// Adding Hints: Annotations
4 | //// Section: 0.
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | class Adder {
10 | fun add(a:Double, b:Double) = a + b
11 | }
12 | class Subtractor {
13 | fun subtract(a:Double, b:Double) = a - b
14 | }
15 |
16 | //----#### SNIPPET #### - 2
17 | val eng = CalculationEngine()
18 | ...
19 | eng.registerAdder(Adder::class, "add")
20 | eng.registerSubtractor(Subtractor::class, "subtract")
21 | ...
22 |
23 | //----#### SNIPPET #### - 3
24 | /**
25 | * @Operator: ADDING
26 | * @Function: add
27 | */
28 | class Adder {
29 | fun add(a:Double, b:Double) = a + b
30 | }
31 |
32 | /**
33 | * @Operator: SUBTRACTING
34 | * @Function: subtract
35 | */
36 | class Subtractor {
37 | fun subtract(a:Double, b:Double) = a - b
38 | }
39 |
--------------------------------------------------------------------------------
/140/src_chapt14_sect001_Annotations_in_Kotlin.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 14:
3 | //// Adding Hints: Annotations
4 | //// Section: 1. Annotations in Kotlin
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | @AnnotationName
10 |
11 | //----#### SNIPPET #### - 2
12 | @AnnotationName(...)
13 |
14 | //----#### SNIPPET #### - 3
15 | @Operator(ADDING)
16 | class Adder {
17 | @OperatorFunction
18 | fun add(a:Double, b:Double) = a + b
19 | }
20 |
21 | @Operator(SUBTRACTING)
22 | class Subtractor {
23 | @OperatorFunction
24 | fun subtract(a:Double, b:Double) = a - b
25 | }
26 |
--------------------------------------------------------------------------------
/140/src_chapt14_sect002_Annotation_Characteristics.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 14:
3 | //// Adding Hints: Annotations
4 | //// Section: 2. Annotation Characteristics
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | annotation class AnnotationName
10 |
11 | //----#### SNIPPET #### - 2
12 | @Target(...)
13 | @Retention(...)
14 | @Repeatable
15 | @MustBeDocumented
16 | annotation class AnnotationName
17 |
--------------------------------------------------------------------------------
/140/src_chapt14_sect003_Applying_Annotations.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 14:
3 | //// Adding Hints: Annotations
4 | //// Section: 3. Applying Annotations
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | class Xyz {
10 | @MyAnnot var d1:Double = 1.0
11 | }
12 |
13 | //----#### SNIPPET #### - 2
14 | @file:JvmName("Foo")
15 | package com.xyz.project
16 | ...
17 |
18 | //----#### SNIPPET #### - 3
19 | // An annotation applying to a file (the implicit
20 | // internal class generated)
21 | @file:Annot
22 | package com.xyz.project
23 | ...
24 |
25 | // An annotation applying to a class, a singleton
26 | // object or an interface
27 | @Annot class TheName ...
28 | @Annot object TheName ...
29 | @Annot interface TheName ...
30 |
31 | // An annotation applying to a function
32 | @Annot fun theName() { ... }
33 |
34 | // An annotation applying to a property
35 | @property:Annot val theName = ...
36 | @Annot var theName = ...
37 | class SomeClass(@property:Annot var param:Type, ...) ...
38 |
39 | // An annotation applying to a function parameter
40 | f(@Annot p:Int, ...) { ... }
41 |
42 | // An annotation applying to a constructor
43 | class TheName @annot constructor(...) ...
44 |
45 | // An annotation applying to a constructor parameter
46 | class SomeClass(@param:Annot val param:Type, ...) ...
47 |
48 | // An annotation applying to a lambda function
49 | val f = @annot { par:Int -> ... }
50 |
51 | // An annotation applying to the datum field
52 | // behind a property
53 | @field:Annot val theName = ...
54 | class SomeClass(@field:Annot val param:Type, ...) ...
55 |
56 | // An annotation applying to a property setter
57 | @set:Annot var theName = ...
58 | var theName = 37 @Annot set(...) { ... }
59 | class SomeClass(@set:Annot var param:Type, ...) ...
60 |
61 | // An annotation applying to a property getter
62 | @get:Annot var theName = ...
63 | var theName = 37 @Annot get() = ...
64 | class SomeClass(@get:Annot var param:Type, ...) ...
65 |
66 | // An annotation applying to a property setter
67 | // parameter
68 | var theName:Int = 37
69 | set(@setparam:Annot p:String) { })
70 |
71 | // An annotation applying to a receiver
72 | @receiver:Annot fun String.xyz() { }
73 |
74 | // An annotation applying to a delegate
75 | class Derived(@delegate:Annot b: Base) : Base by b
76 |
77 | //----#### SNIPPET #### - 4
78 | @Annot(AnotherAnnot)
79 |
--------------------------------------------------------------------------------
/140/src_chapt14_sect004_Annotations_With_Array_Parameter.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 14:
3 | //// Adding Hints: Annotations
4 | //// Section: 4. Annotations With Array Parameter
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | annotation class Annot(vararg val params:String)
10 | ...
11 | @Annot("A", "B", "C", ...) val prop:Int = ...
12 |
13 | //----#### SNIPPET #### - 2
14 | @field:JavaAnnot("A", "B", "C", ...) val prop:Int = ...
15 |
16 | //----#### SNIPPET #### - 3
17 | @Annot(param1 = 37, arrParam = [37, 42, 6], ...)
18 |
--------------------------------------------------------------------------------
/140/src_chapt14_sect005_Reading_Annotations.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 14:
3 | //// Adding Hints: Annotations
4 | //// Section: 5. Reading Annotations
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | TheName::class.annotations
10 |
11 | //----#### SNIPPET #### - 2
12 | property::class.annotations
13 |
14 | //----#### SNIPPET #### - 3
15 | val annot = TheName::class.
16 | findAnnotation()
17 |
18 | //----#### SNIPPET #### - 4
19 | val prop = ClassName::propertyName
20 | val annots = prop.annotations
21 | val annot = prop.
22 | findAnnotation()
23 |
24 | //----#### SNIPPET #### - 5
25 | val prop = ClassName::propertyName
26 | val field = prop.javaField
27 | val annotations = field?.annotations
28 |
29 | //----#### SNIPPET #### - 6
30 | val funName = "functionName"
31 | // <- choose your own
32 | val pars = listOf(Int::class)
33 | // <- choose your own
34 | val function =
35 | TheClass::class.
36 | declaredFunctions.filter {
37 | it.name == funName }
38 | ?.find { f ->
39 | val types = f.valueParameters.map{
40 | it.type.jvmErasure}
41 | types == pars
42 | }
43 |
--------------------------------------------------------------------------------
/140/src_chapt14_sect007_Custom_Annotations.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 14:
3 | //// Adding Hints: Annotations
4 | //// Section: 7. Custom Annotations
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | @Target(...)
10 | @Retention(...)
11 | @Repeatable
12 | @MustBeDocumented
13 | annotation class AnnotationName
14 |
15 | //----#### SNIPPET #### - 2
16 | [possibly meta-annotations]
17 | annotation class AnnotationName(val p1:Type1,
18 | val p2:Type2, ...)
19 |
20 | //----#### SNIPPET #### - 3
21 | @Target(AnnotationTarget.VALUE_PARAMETER)
22 | @Retention(AnnotationRetention.RUNTIME)
23 | annotation class NotZero()
24 |
25 | //----#### SNIPPET #### - 4
26 | class Calculator {
27 | enum class Operator(val oper:String) {
28 | MULTIPLY("multiply"),
29 | DIVIDE("divide")
30 | }
31 |
32 | fun operator(oper:Operator,
33 | vararg params:Double): Double {
34 | val f = Calculator::class.declaredFunctions.
35 | find { it.name == oper.oper }
36 | f?.valueParameters?.forEachIndexed { ind, p ->
37 | p.findAnnotation()?.run {
38 | if (params[ind] == 0.0)
39 | throw RuntimeException(
40 | "Parameter ${ind} not unequal 0.0")
41 | }
42 | }
43 | val ps = arrayOf(this@Calculator,
44 | *(params).toList().toTypedArray())
45 | return (f?.call(*ps) as Double?) ?: 0.0
46 | }
47 |
48 | fun multiply(p1:Double, p2:Double) : Double {
49 | return p1 * p2
50 | }
51 |
52 | fun divide(p1:Double, @NotZero p2:Double) : Double {
53 | return p1 / p2
54 | }
55 | }
56 |
57 | //----#### SNIPPET #### - 5
58 | Calculator().
59 | operator(Calculator.Operator.DIVIDE,
60 | 1.0, 1.0)
61 |
--------------------------------------------------------------------------------
/160/src_chapt16_sect002_Classes.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 16:
3 | //// The Collectionsnewline API
4 | //// Section: 2. Classes
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | var l:MutableList = ArrayList()
10 | // ... = ArrayList() is unnecessary, since
11 | // Kotlin can infer the type.
12 |
--------------------------------------------------------------------------------
/160/src_chapt16_sect003_Generator_Functions.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 16:
3 | //// The Collectionsnewline API
4 | //// Section: 3. Generator Functions
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | listOf(1, 5, 7, 9)
10 |
--------------------------------------------------------------------------------
/160/src_chapt16_sect014_Joining.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 16:
3 | //// The Collectionsnewline API
4 | //// Section: 14. Joining
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | fun Iterable.joinToString(
10 | separator: CharSequence = ", ",
11 | prefix: CharSequence = "",
12 | postfix: CharSequence = "",
13 | limit: Int = -1,
14 | truncated: CharSequence = "...",
15 | transform: (E) -> CharSequence = null
16 | ): String
17 |
--------------------------------------------------------------------------------
/160/src_chapt16_sect016_Zipping.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 16:
3 | //// The Collectionsnewline API
4 | //// Section: 16. Zipping
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | class Employee {
10 | ...
11 | fun setSalary(year:Int, salary:Double) {}
12 | }
13 |
14 | val employees = ... // list
15 | val newSalaries = ... // list
16 | val newYear = 2018
17 | val newEmployees = mutableListOf()
18 | for(ind in employees.indices) {
19 | val e = employees[ind]
20 | val sal = newSalaries[ind]
21 | e.setSalary(newYear, sal)
22 | newEmployees.add(e)
23 | }
24 |
25 | //----#### SNIPPET #### - 2
26 | Iterable.zip(
27 | other: Iterable
28 | ): List>
29 |
30 | //----#### SNIPPET #### - 3
31 | val employees = ... // list
32 | val newSalaries = ... // list
33 | val newYear = 2018
34 | val newEmployees = employees.zip(newSalaries).
35 | map{ p ->
36 | p.first.setSalary(newYear, p.second)
37 | p.first
38 | }
39 |
40 | //----#### SNIPPET #### - 4
41 | Iterable>.unzip():
42 | Pair, List>
43 |
44 | //----#### SNIPPET #### - 5
45 | list.map { item ->
46 | Pair(item.something, item.somethingElse)
47 | }.unzip()
48 |
--------------------------------------------------------------------------------
/160/src_chapt16_sect018_Sequences.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 16:
3 | //// The Collectionsnewline API
4 | //// Section: 18. Sequences
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | sequenceOf(1, 2, 7, 5)
10 |
11 | //----#### SNIPPET #### - 2
12 | iter.asSequence()
13 |
14 | //----#### SNIPPET #### - 3
15 | // Signature:
16 | // fun generateSequence(
17 | // nextFunction: () -> T?
18 | // ): Sequence
19 |
20 | var iterVar = 0
21 | val seq = generateSequence {
22 | iterVar++
23 | }
24 |
25 | //----#### SNIPPET #### - 4
26 | fun generateSequence(
27 | seed: T?,
28 | nextFunction: (T) -> T?
29 | ): Sequence
30 | // or
31 | fun generateSequence(
32 | seedFunction: () -> T?,
33 | nextFunction: (T) -> T?
34 | ): Sequence
35 |
36 | //----#### SNIPPET #### - 5
37 | val seq = generateSequence(
38 | seed = 0,
39 | nextFunction = { curr -> curr + 1 }
40 | )
41 |
42 | // example usage:
43 | seq.take(10).forEach { i ->
44 | // i will have values 0, 1, 2, ..., 9
45 | ...
46 | }
47 |
48 | //----#### SNIPPET #### - 6
49 | val seqFib = generateSequence(
50 | seed = Pair(1,1),
51 | nextFunction = { curr ->
52 | Pair(curr.second, curr.first + curr.second)
53 | }
54 | )
55 |
56 | // example usage
57 | seqFib.take(10).map { it.second }.forEach {
58 | Log.e("LOG", "fib: " + it)
59 | }
60 |
61 | //----#### SNIPPET #### - 7
62 | val p = seqFib.take(40).last
63 | val gr = p.second * 1.0 / p.first
64 | // = 1.618033988749895
65 |
66 | //----#### SNIPPET #### - 8
67 | fun sequence(
68 | block: suspend SequenceScope.() -> Unit
69 | ): Sequence
70 |
71 | //----#### SNIPPET #### - 9
72 | Sequence { iterator(block) }
73 |
74 | //----#### SNIPPET #### - 10
75 | yieldAll([some implementation of Iterable])
76 | // or
77 | yieldAll([some implementation of Iterator])
78 | // or
79 | yieldAll([some implementation of Sequence])
80 |
81 | //----#### SNIPPET #### - 11
82 | val sequence = sequence {
83 | // This is an iterable:
84 | yieldAll(1..10 step 2)
85 | }
86 |
87 | // Usage example:
88 | sequence.take(8).forEach {
89 | Log.e("LOG", it.toString())
90 | }
91 | // -> 1, 3, 5, 7, 9
92 |
--------------------------------------------------------------------------------
/170/src_chapt17_sect001_The_Math_API.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 17:
3 | //// More APIs
4 | //// Section: 1. The Math API
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | import java.lang.Math
10 |
11 | //----#### SNIPPET #### - 2
12 | import kotlin.math.sin
13 | ...
14 | val x = sin(1.562)
15 |
16 | //----#### SNIPPET #### - 3
17 | import kotlin.math.absoluteValue
18 | ...
19 | val x:Double = -3.5
20 | val y = x.absoluteValue // -> 3.5
21 |
--------------------------------------------------------------------------------
/170/src_chapt17_sect002_The_Date_Time_API__API_Level_25_or_Less.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 17:
3 | //// More APIs
4 | //// Section: 2. The Date-Time API, API Level 25 or Less
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | import java.util.Date
10 | import java.util.GregorianCalendar
11 | import java.text.SimpleDateFormat
12 |
13 | val timeMillis:Long = System.currentTimeMillis()
14 | val d = Date()
15 | val cal = GregorianCalendar()
16 | val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
17 |
18 | //----#### SNIPPET #### - 2
19 | val t1 = System.currentTimeMillis()
20 | ...
21 | Log.d("LOG", "Calculation took " +
22 | (System.currentTimeMillis() - t1) + "ms")
23 |
24 | //----#### SNIPPET #### - 3
25 | import java.util.Date
26 | ...
27 | val d = Date() // current time
28 | Log.d("LOG", d.toString())
29 | // -> s.th. like
30 | // Sun Jan 13 10:12:26 GMT+01:00 2019
31 |
32 | //----#### SNIPPET #### - 4
33 | import java.util.Date
34 | ...
35 | val d = Date() // current time
36 | val tm = d.time // ms since 1970-01-01T00:00:00 UTC
37 |
38 | //----#### SNIPPET #### - 5
39 | import java.util.Date
40 | import java.util.Calendar
41 | import java.util.GregorianCalendar
42 | import java.util.TimeZone
43 | ...
44 | val cal = GregorianCalendar()
45 | // <- will hold the current time
46 |
47 | cal.timeZone = TimeZone.getTimeZone("US/Hawaii")
48 | // Note: TimeZone.getAvailableIDs().forEach {
49 | // Log.e("LOG","!!! " + it) }
50 | // shows a list
51 |
52 | // Set to current time
53 | cal.time = Date()
54 |
55 | // Set to 2018-02-01T13:27:44
56 | cal.set(2018, Calendar.FEBRUARY, 1, 13, 27 ,44)
57 |
58 | val month = cal.get(Calendar.MONTH)
59 | val hour = cal.get(Calendar.HOUR_OF_DAY)
60 |
61 | //----#### SNIPPET #### - 6
62 | import java.util.Date
63 | import java.text.SimpleDateFormat
64 | import java.util.Locale
65 | ...
66 |
67 | val d = Date() // now
68 | val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm")
69 | Log.d("LOG", sdf.format(d)) // -> 2019-01-13 13:41
70 |
71 | val loc = Locale("en")
72 | val sdf2 = SimpleDateFormat("yyyy-MMM-dd HH:mm", loc)
73 | Log.d("LOG", sdf2.format(d)) // -> 2019-Jan-13 13:41
74 |
75 | val d2:Date = sdf.parse("2018-12-12 17:13")
76 | Log.d("LOG", d2.toString())
77 | // -> Wed Dec 12 17:13:00 GMT+01:00 2018
78 |
79 | //----#### SNIPPET #### - 7
80 | import java.text.SimpleDateFormat
81 | import java.util.Date
82 | import java.util.TimeZone
83 | ...
84 | val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm")
85 | sdf.timeZone = TimeZone.getTimeZone("US/Hawaii")
86 |
87 | val d:Date = sdf.parse("2018-12-12 17:13")
88 | Log.d("LOG", d.toString())
89 | // -> Thu Dec 13 04:13:00 GMT+01:00 2018
90 |
--------------------------------------------------------------------------------
/170/src_chapt17_sect003_The_Date_Time_API__API_Level_26_or_Greater.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 17:
3 | //// More APIs
4 | //// Section: 3. The Date-Time API, API Level 26 or Greater
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | android {
10 | ...
11 | defaultConfig {
12 | ...
13 | minSdkVersion 26
14 | ...
15 | }
16 | ...
17 | }
18 |
19 | //----#### SNIPPET #### - 2
20 | import java.time.*
21 |
22 | // current day in the default time zone
23 | val ld1 : LocalDate = LocalDate.now()
24 |
25 | // "Now" corresponds to different days in different
26 | // time zones. The following allows to specify a
27 | // different time zone
28 | val z2 = ZoneId.of("UTC+01")
29 | val ld2 : LocalDate = LocalDate.now(z2)
30 |
31 | val ld3 = LocalDate.of(2018, Month.MARCH, 27)
32 | val ld4 = LocalDate.of(2018, 3, 27) // the same
33 |
34 | val lt1 : LocalTime = LocalTime.now()
35 | val lt2 = LocalTime.now(z2) // different time zone
36 | val lt3 = LocalTime.of(23, 27, 55) // 23:27:55
37 |
38 | val ldt1 = LocalDateTime.now()
39 | val ldt2 = LocalDateTime.now(z2)
40 | val ldt3 = LocalDateTime.of(
41 | 2018, Month.APRIL, 23,
42 | 23, 44, 12)
43 | // <- 2018-04-23T23:44:12
44 |
45 | //----#### SNIPPET #### - 3
46 | import java.time.*
47 | import java.time.format.*
48 |
49 | // Parse ISO-8601
50 | val ld1 = LocalDate.parse("2019-02-13")
51 |
52 | // Parse other formats. For the format specification,
53 | // see API documentation of class DateTimeFormatter.
54 | val formatter1 =
55 | DateTimeFormatter.ofPattern("yyyy MM dd")
56 | val ld2 = LocalDate.parse("2019 02 13", formatter1)
57 |
58 |
59 | val lt1 = LocalTime.parse("21:17:23")
60 | val lt2 = LocalTime.parse("21:17:23.3734")
61 |
62 | val formatter2 =
63 | DateTimeFormatter.ofPattern("HH|mm|ss")
64 | val lt3 = LocalTime.parse("21|17|23", formatter2)
65 |
66 |
67 | val ldt1 = LocalDateTime.parse("2019-02-13T21:17:23")
68 | val ldt2 = LocalDateTime.parse(
69 | "2019-02-13T21:17:23.3734")
70 |
71 | val formatter3 = DateTimeFormatter.ofPattern(
72 | "yyyy.MM.dd.HH.mm.ss")
73 | val ldt3 = LocalTime.parse("2019.04.23.17.45.23",
74 | formatter3)
75 |
76 | //----#### SNIPPET #### - 4
77 | import android.util.Log
78 | import java.time.*
79 | import java.time.format.*
80 |
81 | val s1 = LocalDate.now().format(
82 | DateTimeFormatter.ofPattern("yyyy|MM|dd"))
83 | Log.d("LOG","s1 = ${s1}") // -> 2019|01|14
84 |
85 | val s2 = LocalDate.now().format(
86 | DateTimeFormatter.ISO_LOCAL_DATE)
87 | Log.d("LOG","s2 = ${s2}") // -> 2019-01-14
88 |
89 |
90 | val s3 = LocalTime.now().format(
91 | DateTimeFormatter.ofPattern("HH mm ss"))
92 | Log.d("LOG","s3 = ${s3}") // -> 14 46 20
93 |
94 | val s4 = LocalTime.now().format(
95 | DateTimeFormatter.ISO_LOCAL_TIME)
96 | Log.d("LOG","s4 = ${s4}") // 14:46:20.503
97 |
98 |
99 | val s5 = LocalDateTime.now().format(
100 | DateTimeFormatter.ofPattern(
101 | "yyyy MM dd - HH mm ss"))
102 | Log.d("LOG","s5 = ${s5}") // -> 2019 01 14 - 14 46 20
103 |
104 | val s6 = LocalDateTime.now().format(
105 | DateTimeFormatter.ISO_LOCAL_DATE_TIME)
106 | Log.d("LOG","s6 = ${s6}") // -> 2019-01-14T14:46:20.505
107 |
108 | //----#### SNIPPET #### - 5
109 | import java.time.*
110 | import java.time.temporal.*
111 |
112 | val ld = LocalDate.now()
113 | val lt = LocalTime.now()
114 | val ldt = LocalDateTime.now()
115 |
116 | val ld2 = ld.minusDays(7L)
117 | val ld3 = ld.plusWeeks(2L)
118 | val ld4 = ld.with(ChronoField.MONTH_OF_YEAR, 11L)
119 |
120 | val lt2 = lt.plus(Duration.of(2L, ChronoUnit.SECONDS))
121 | val lt3 = lt.plusSeconds(2L) // same
122 |
123 | val ldt2 = ldt.plusWeeks(2L).minusHours(2L)
124 |
125 | //----#### SNIPPET #### - 6
126 | import java.time.*
127 |
128 | val ldt : LocalDateTime = ...
129 | val secs = ldt.toEpochSecond(ZoneOffset.of("+01:00"))
130 |
131 | //----#### SNIPPET #### - 7
132 | import java.time.*
133 |
134 | val inz1 = Instant.now() // default timezone
135 |
136 | // Specify timezone
137 | val inz2 = Instant.now(Clock.system(
138 | ZoneId.of("America/Buenos_Aires")))
139 |
140 | val secondsSince1970 : Long = 1_000_000_000L
141 | val nanoAdjustment : Long = 300_000_000 // 300ms
142 | val inz3 = Instant.ofEpochSecond(
143 | secondsSince1970, nanoAdjustment)
144 |
145 | // "Z" is UTC ("Zulu" time)
146 | val inz4 = Instant.parse("2018-01-23T23:33:14.513Z")
147 |
148 | // Uniform converter, for the ZonedDateTime class
149 | // see below
150 | val inz5 = Instant.from(
151 | ZonedDateTime.parse(
152 | "2019-02-13T21:17:23+01:00[Europe/Paris]"))
153 |
154 | //----#### SNIPPET #### - 8
155 | import java.time.*
156 | import java.time.format.DateTimeFormatter
157 |
158 | // Get now ------------------------------------------
159 |
160 | // System clock, default timezone
161 | val ot1 = OffsetTime.now()
162 | val odt1 = OffsetDateTime.now()
163 |
164 | // Use a different clock
165 | val clock:Clock = ...
166 | val ot2 = OffsetTime.now(clock)
167 | val odt2 = OffsetDateTime.now(clock)
168 |
169 | // Use a different timezone
170 | val ot3 = OffsetTime.now(
171 | ZoneId.of("America/Buenos_Aires"))
172 | val odt3 = OffsetDateTime.now(
173 | ZoneId.of("America/Buenos_Aires"))
174 |
175 | // From time details --------------------------------
176 |
177 | val ot4 = OffsetTime.of(23, 17, 3, 500_000_000,
178 | ZoneOffset.of("-02:00"))
179 | val odt4 = OffsetDateTime.of(
180 | 1985, 4, 23, // 19685-04-23
181 | 23, 17, 3, 500_000_000, // 23:17:03.5
182 | ZoneOffset.of("+02:00"))
183 |
184 | // Parsed -------------------------------------------
185 |
186 | val ot5 = OffsetTime.parse("16:15:30+01:00")
187 | val odt5 = OffsetDateTime.parse(
188 | "2007-12-03T17:15:30-08:00")
189 | val ot6 = OffsetTime.parse("16 15 +00:00",
190 | DateTimeFormatter.ofPattern("HH mm XXX"))
191 | val odt6 = OffsetDateTime.parse(
192 | "20181115 - 231644 +02:00",
193 | DateTimeFormatter.ofPattern(
194 | "yyyyMMdd - HHmmss XXX"))
195 |
196 | // From other objects -------------------------------
197 |
198 | val lt = LocalTime.parse("16:14:27.235")
199 | val ld = LocalDate.parse("2018-05-24")
200 | val inz = Instant.parse("2018-01-23T23:33:14.513Z")
201 | val ot7 = OffsetTime.of(lt,
202 | ZoneOffset.of("+02:00"))
203 | val odt7 = OffsetDateTime.of(ld, lt,
204 | ZoneOffset.of("+02:00"))
205 | val ot8 = OffsetTime.ofInstant(inz,
206 | ZoneId.of("America/Buenos_Aires"))
207 | val odt8 = OffsetDateTime.ofInstant(inz,
208 | ZoneId.of("America/Buenos_Aires"))
209 |
210 | val zdt = ZonedDateTime.of( // see below
211 | 2018, 2, 27, // 2018-02-27
212 | 23, 27, 33, 0, // 23:27:33.0
213 | ZoneId.of("Pacific/Tahiti"))
214 | val odt9 = zdt.toOffsetDateTime()
215 |
216 | // uniform converter
217 | val ot10 = OffsetTime.from(zdt)
218 | val odt10 = OffsetDateTime.from(zdt)
219 |
220 | //----#### SNIPPET #### - 9
221 | import java.time.*
222 |
223 | val ot = OffsetTime.parse("16:15:30+01:00")
224 | val lt : LocalTime = ot.toLocalTime()
225 |
226 | val odt = OffsetDateTime.parse(
227 | "2007-12-03T17:15:30-08:00")
228 | val ldt : LocalDateTime = odt.toLocalDateTime()
229 | val lt2 : LocalTime = odt.toLocalTime()
230 | val ld2 : LocalDate = odt.toLocalDate()
231 | val ot2 : OffsetTime = odt.toOffsetTime()
232 |
233 | val zdt : ZonedDateTime = odt.toZonedDateTime()
234 | // see below for class ZonedDateTime
235 |
236 | //----#### SNIPPET #### - 10
237 | import java.time.*
238 |
239 | // Get "now" using the system clock and the default
240 | // time-zone from your operating system.
241 | val zdt1 = ZonedDateTime.now()
242 |
243 | // Get "now" using a time-zone. To list all available
244 | // predefined zone IDs, try
245 | // Log.d("LOG", ZoneId.getAvailableZoneIds().
246 | // joinToString { it + "\n" })
247 | val z2 = ZoneId.of("UTC+01")
248 | val zdt2 = ZonedDateTime.now(z2)
249 |
250 | // Get "now" using an instance of Clock
251 | val clock3 = Clock.systemUTC()
252 | val zdt3 = ZonedDateTime.now(clock3)
253 |
254 | //----#### SNIPPET #### - 11
255 | import java.time.*
256 |
257 | val z4 = ZoneId.of("Pacific/Tahiti")
258 | val zdt4 = ZonedDateTime.of(
259 | 2018, 2, 27, // 2018-02-27
260 | 23, 27, 33, 0, // 23:27:33.0
261 | z4)
262 | // The 7th par is nanoseconds, so for
263 | // 23:27:33.5 you have to enter
264 | // 500_000_000 here
265 |
266 | val localDate = LocalDate.parse("2018-02-27")
267 | val localTime = LocalTime.parse("23:44:55")
268 | val zdt5 = ZonedDateTime.of(localDate, localTime,
269 | ZoneId.of("America/Buenos_Aires"))
270 |
271 | val ldt = LocalDateTime.parse("2018-02-27T23:44:55.3")
272 | val zdt6 = ZonedDateTime.of(ldt,
273 | ZoneId.of("America/Buenos_Aires"))
274 |
275 | val inz = Instant.parse("2018-01-23T23:33:14.513Z")
276 | val zdt7 = ZonedDateTime.ofInstant(inz,
277 | ZoneId.of("America/Buenos_Aires"))
278 |
279 | val zdt8 = ZonedDateTime.parse(
280 | "2018-01-23T23:33:14Z[America/Buenos_Aires]")
281 |
282 | //----#### SNIPPET #### - 12
283 | import java.time.*
284 | import java.time.format.DateTimeFormatter
285 |
286 | val zdt1 = ZonedDateTime.parse(
287 | "2007-12-03T10:15:30+01:00[Europe/Paris]")
288 |
289 | val formatter = DateTimeFormatter.ofPattern(
290 | "HH:mm:ss.SSS")
291 | // See DateTimeFormatter API docs for more options
292 | val str = zdt1.format(formatter)
293 |
294 | //----#### SNIPPET #### - 13
295 | import java.time.*
296 |
297 | val ldt = LocalDateTime.parse("2018-02-27T23:44:55.3")
298 | val zdt = ZonedDateTime.of(ldt,
299 | ZoneId.of("America/Buenos_Aires"))
300 |
301 | val ldt2 = zdt.toLocalTime()
302 |
303 | //----#### SNIPPET #### - 14
304 | import java.time.*
305 | import java.time.temporal.ChronoUnit
306 |
307 | val ldt1 = LocalDateTime.parse("2018-01-23T17:23:00")
308 | val ldt2 = LocalDateTime.parse("2018-01-24T16:13:10")
309 | val ldt3 = LocalDateTime.parse("2020-01-24T16:13:10")
310 |
311 | // Getting a duration: ------------------------------
312 |
313 | val d1 = Duration.between(ldt1, ldt2)
314 | // Note: this works also for Instant and ZonedDateTime
315 | // objects
316 |
317 | val d2 = Duration.of(27L, ChronoUnit.HOURS) // 27hours
318 |
319 | val d3 = Duration.ZERO.
320 | plusDays(3L).
321 | plusHours(4L).
322 | minusMinutes(78L)
323 |
324 | val d4 = Duration.parse("P2DT3H4M")
325 | // <- 2 days, 3 hrs, 4 minutes
326 | // For more specifiers, see the API documentation
327 | // of Duration.parse()
328 |
329 | // Getting a period: --------------------------------
330 |
331 | val ld1 = LocalDate.parse("2018-04-23")
332 | val ld2 = LocalDate.parse("2018-08-16")
333 |
334 | val p1 = Period.between(ld1, ld2)
335 | // Note, end date not inclusive
336 |
337 | val p2 = Period.of(2, 3, -1)
338 | // <- 2 years + 3 months - 1 day
339 |
340 | val p3 = Period.parse("P1Y2M-3D")
341 | // <- 1 year + 2 months - 3 days
342 | // For more specifiers, see the API documentation
343 | // of Period.parse()
344 |
345 | //----#### SNIPPET #### - 15
346 | import java.time.*
347 |
348 | // Duration operations: ------------------------------
349 |
350 | val d = Duration.parse("P2DT3H4M")
351 | // <- 2 days, 3 hrs, 4 minutes
352 |
353 | val d2 = d.plusDays(3L)
354 | // also: .minusDays(33L)
355 | // or .plusHours(2L) or .minusHours(1L)
356 | // or .plusMinutes(77L) or .minusMinutes(7L)
357 | // or .plusSeconds(23L) or .minusSeconds(5L)
358 | // or .plusMillis(11L) or .minusMillis(55L)
359 | // or .plusNanos(1000L) or .minusNanos(5_000_000L)
360 |
361 | val d3 = d.abs() // make positive
362 | val d4 = d.negated() // swap sign
363 | val d5 = d.multipliedBy(3L) // three times a long
364 | val d6 = d.dividedBy(2L) // half as long
365 |
366 | // Period operations: --------------------------------
367 |
368 | val p = Period.of(2, 3, -1)
369 | // <- 2 years + 3 months - 1 day
370 |
371 | val p2 = p.normalized()
372 | // <- possibly adjusts the year to make the month lie
373 | // inside [-11;+11]
374 |
375 | val p3 = p.negated()
376 |
377 | val p4 = p.minusYears(11L)
378 | // also: .plusYears(3L)
379 | // or .minusMonths(4L) or .plusMonths(2L)
380 | // or .minusDays(40L) or .plusDays(5L)
381 |
382 | val p5 = p.multipliedBy(5) // 5 times as long
383 |
384 | //----#### SNIPPET #### - 16
385 | import java.time.*
386 |
387 | val d = Duration.parse("P2DT3H4M")
388 |
389 | val p = Period.of(2, 3, -1)
390 | // <- 2 years + 3 months - 1 day
391 |
392 | val ld = LocalDate.parse("2018-04-23")
393 | val lt = LocalTime.parse("17:13:12")
394 | val ldt = LocalDateTime.of(ld, lt)
395 | val zdt = ZonedDateTime.parse(
396 | "2007-12-03T10:15:30+01:00[Europe/Paris]")
397 | val inz = Instant.parse("2018-01-23T23:33:14.513Z")
398 |
399 | // ---- Using a LocalDate
400 | val ld2 = ld.plus(p) // or .minus(p)
401 | // val ld3 = ld.plus(d) // -> exception
402 | // val ld4 = ld.minus(d) // -> exception
403 |
404 | // ---- Using a LocalTime
405 | val lt2 = lt.plus(d) // or .minus(d)
406 | // val lt3 = lt.minus(p) // -> exception
407 | // val lt4 = lt.plus(p) // -> exception
408 |
409 | // ---- Using a LocalDateTime
410 | val ldt2 = ldt.plus(d) // or .minus(d)
411 | val ldt3 = ldt.plus(p) // or .minus(p)
412 |
413 | // ---- Using a ZonedDateTime
414 | val zdt2 = zdt.plus(d) // or .minus(d)
415 | val zdt3 = zdt.plus(p) // or .minus(p)
416 |
417 | // ---- Using an Instant
418 | val inz2 = inz.plus(d) // or .minus(d)
419 | // val inz3 = inz.minus(p) // -> exception
420 | // val inz4 = inz.plus(p) // -> exception
421 |
422 | //----#### SNIPPET #### - 17
423 | import java.time.*
424 |
425 | val clock : Clock = ...
426 | val ldt = LocalDateTime.now(clock)
427 | val zdt = ZonedDateTime.now(clock)
428 | val inz = Instant.now(clock)
429 |
430 | //----#### SNIPPET #### - 18
431 | import java.time.*
432 |
433 | val myClock = object : Clock() {
434 | override fun withZone(zone: ZoneId?): Clock {
435 | // Supposed to return a copy of this clock
436 | // with a different time zone
437 | return this
438 | }
439 |
440 | override fun getZone(): ZoneId {
441 | // Supposed to return the zone ID
442 | return ZoneId.of("Z")
443 | }
444 |
445 | override fun instant(): Instant {
446 | // This is the engine of the clock. It must
447 | // provide an Instant
448 | return Instant.parse("2018-01-23T23:33:14Z")
449 | }
450 | }
451 |
452 | ... use myClock
453 |
--------------------------------------------------------------------------------
/170/src_chapt17_sect004_Input_And_Output.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 17:
3 | //// More APIs
4 | //// Section: 4. Input And Output
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | println("Hello World")
10 |
11 | //----#### SNIPPET #### - 2
12 | import java.io.File
13 |
14 | // We are inside an Activity or other Context!
15 | val dataDir:File = getFilesDir()
16 |
17 | //----#### SNIPPET #### - 3
18 | dataDir.resolve("a.txt").takeIf{ !it.exists() }.
19 | appendText("Hello World A")
20 | dataDir.resolve("b.txt").takeIf{ !it.exists() }.
21 | appendText("Hello World B")
22 | File(dataDir,"dir1").mkdirs()
23 | dataDir.resolve("dir1").resolve("a.txt").
24 | takeIf{ !it.exists() }.
25 | appendText("Hello World dir1-A")
26 |
27 | //----#### SNIPPET #### - 4
28 | val someDir:File = ...
29 | val file:File = someDir.resolve("fileName")
30 |
31 | //----#### SNIPPET #### - 5
32 | dataDir.walk().maxDepth(1).forEach { file ->
33 | Log.d("LOG", file.toString())
34 | }
35 |
36 | //----#### SNIPPET #### - 6
37 | dataDir.walk().filter { it.isFile() }.forEach {
38 | file ->
39 | Log.d("LOG", file.toString())
40 | }
41 |
42 | //----#### SNIPPET #### - 7
43 | dataDir.walk().filter { it.endsWith(".txt") }.forEach {
44 | file ->
45 | Log.d("LOG", file.toString())
46 | }
47 |
48 | //----#### SNIPPET #### - 8
49 | dataDir.walk().filter {
50 | it.name.matches(".*invoice\\d\\d.*\\.txt")
51 | }.forEach {
52 | file ->
53 | Log.d("LOG", file.toString())
54 | }
55 |
56 | //----#### SNIPPET #### - 9
57 | val file = dataDir.resolve("a.txt")
58 | // or any other file
59 |
60 | // Write to the file
61 | file.writeText("In the house, there was no light")
62 |
63 | // Append to the file
64 | file.appendText("\nIn the house, there was no light")
65 |
66 | //----#### SNIPPET #### - 10
67 | val file = dataDir.resolve("a.txt")
68 | val bytes = byteArrayOf(27, 34, 13, 47, 50)
69 |
70 | // Write to the file
71 | file.writeBytes(bytes)
72 |
73 | // Append to the file
74 | file.appendBytes(bytes)
75 |
76 | //----#### SNIPPET #### - 11
77 | val file = dataDir.resolve("a.txt")
78 | val fileText:String = file.readText()
79 |
80 | //----#### SNIPPET #### - 12
81 | val file = dataDir.resolve("a.txt")
82 | val fileText:String = file.readText(
83 | Charsets.ISO_8859_1)
84 |
85 | //----#### SNIPPET #### - 13
86 | val file = dataDir.resolve("a.txt")
87 | val fileBytes:ByteArray = file.readBytes()
88 |
89 | //----#### SNIPPET #### - 14
90 | val file = dataDir.resolve("a.txt")
91 |
92 | val allLines = file.readLines()
93 | allLines.forEach { ln ->
94 | // do something with the line (a String)
95 | }
96 |
97 | //----#### SNIPPET #### - 15
98 | val file = dataDir.resolve("a.txt")
99 |
100 | // Only API level > 25
101 | file.bufferedReader.use {
102 | it.lines().forEach { ln ->
103 | // do something with the line (a String)
104 | }
105 | }
106 |
107 | //----#### SNIPPET #### - 16
108 | import java.io.File
109 | ...
110 |
111 | val file = dataDir.resolve("a.txt")
112 |
113 | // Buffer size implementation dependent
114 | file.forEachBlock{ buffer:ByteArray, bytesRead:Int ->
115 | // do something with the buffer
116 | }
117 |
118 | // Or, if you want to prescribe the buffer size
119 | file.forEachBlock(512) { buffer, bytesRead ->
120 | // do something with the buffer
121 | }
122 |
123 | //----#### SNIPPET #### - 17
124 | import java.io.File
125 | ...
126 |
127 | val file:File = ...
128 | val wasDeleted:Boolean = file.delete()
129 |
130 | //----#### SNIPPET #### - 18
131 | import java.io.File
132 | ...
133 |
134 | val file:File = ...
135 | val wasDeleted:Boolean = file.deleteRecursively()
136 |
137 | //----#### SNIPPET #### - 19
138 | import java.io.File
139 | ...
140 |
141 | val file:File = ...
142 | file.deleteOnExit()
143 |
144 | //----#### SNIPPET #### - 20
145 | import java.io.File
146 | ...
147 |
148 | val prefix = "tmpFile"
149 | val suffix = ".tmp"
150 | val tmpFile:File = File.createTempFile(prefix, suffix)
151 | tmpFile.deleteOnExit()
152 |
153 | ... use tmpFile
154 |
155 | //----#### SNIPPET #### - 21
156 | import java.io.File
157 | ...
158 |
159 | val file1:File = ...
160 | val file2:File = ...
161 |
162 | f1.copyTo(f2) // f2 must not exist
163 | f1.copyTo(f2, true) // overwrite if necessary
164 |
165 | // To fine-tune performance, you can tweak the
166 | // buffer-size
167 | f1.copyTo(f2, bufferSize = 4096)
168 |
169 | //----#### SNIPPET #### - 22
170 | import java.io.File
171 | ...
172 |
173 | val dir1:File = ...
174 | val dir2:File = ...
175 |
176 | f1.copyRecursively(f2) // f2 must not exist
177 | f1.copyRecursively(f2, true) // overwrite if necessary
178 |
179 | // To fine-tune error handling, you can add a handler.
180 | // Otherwise an IOException gets thrown.
181 | f1.copyRecursively(f2, onError = {
182 | file:File, ioException:IOException ->
183 | // do something.
184 |
185 | // What to do now? Just skip this file, or
186 | // terminate the complete function?
187 | OnErrorAction.SKIP // or .TERMINATE
188 | })
189 |
190 | //----#### SNIPPET #### - 23
191 | import java.io.File
192 | ...
193 |
194 | val file1:File = ...
195 | val file2:File = ...
196 |
197 | file1.renameTo(file2)
198 |
199 | //----#### SNIPPET #### - 24
200 | import java.io.File
201 | import java.util.Date
202 | ...
203 |
204 | val file = dataDir.resolve("a.txt")
205 | val log = { msg:String -> Log.d("LOG", msg) }
206 |
207 | log("Name: " + file.name)
208 | log("The file exists: " + file.exists())
209 | log("You can read the file: " + file.canRead())
210 | log("You can write to the file: " + file.canWrite())
211 | log("Is a directory: " + file.isDirectory())
212 | log("Is a real file: " + file.isFile())
213 | log("Last modified: " + Date(file.lastModified()))
214 | log("Length: " + file.length())
215 |
216 | //----#### SNIPPET #### - 25
217 | import java.net.URL
218 | import kotlin.concurrent.thread
219 |
220 | thread {
221 | val contents:String =
222 | URL("http://www.example.com/something.txt").
223 | readText()
224 |
225 | val isoContents =
226 | URL("http://www.example.com/something.txt").
227 | readText(Charsets.ISO_8859_1)
228 |
229 | val img:ByteArray =
230 | URL("http://www.example.com/somepic.jpg").
231 | readBytes()
232 | }
233 |
--------------------------------------------------------------------------------
/170/src_chapt17_sect005_Using_Reflection.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 17:
3 | //// More APIs
4 | //// Section: 5. Using Reflection
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | import android.util.Log
10 |
11 | open class MyBase(val baseProp:Int)
12 | class MyClass(var prop1:Int) :
13 | java.io.Serializable, MyBase(13) {
14 | var prop2:String
15 | get() = "Hi"
16 | set(value) { /* ignore */ }
17 |
18 | init {
19 | Log.d("LOG", "Hello from init")
20 | }
21 |
22 | fun function(i:Int):Int {
23 | return prop1 * i
24 | }
25 | }
26 |
27 | val instance = MyClass(42)
28 |
29 | //----#### SNIPPET #### - 2
30 | val clazz = MyClass::class
31 |
32 | // We can also get it from instances:
33 | val clazz = instance::class
34 |
35 | //----#### SNIPPET #### - 3
36 | import android.util.Log
37 | import kotlin.reflect.*
38 | import kotlin.reflect.full.*
39 |
40 | Log.d("LOG", "**** constructors")
41 | clazz.constructors.forEach { c ->
42 | Log.d("LOG", c.toString())
43 | }
44 |
45 | // show only our own properties
46 | Log.d("LOG", "**** declaredMemberProperties")
47 | clazz.declaredMemberProperties.forEach { p ->
48 | Log.d("LOG", p.toString())
49 | }
50 |
51 | // show also inherited properties
52 | Log.d("LOG", "**** memberProperties")
53 | clazz.memberProperties.forEach { p ->
54 | Log.d("LOG", p.toString())
55 | }
56 |
57 | // show only our own functions
58 | Log.d("LOG", "**** declaredFunctions")
59 | clazz.declaredFunctions.forEach { f ->
60 | Log.d("LOG", f.toString())
61 | }
62 |
63 | // show also inherited functions
64 | Log.d("LOG", "**** functions")
65 | clazz.functions.forEach { f ->
66 | Log.d("LOG", f.toString())
67 | }
68 |
69 | //----#### SNIPPET #### - 4
70 | val p1: KProperty1 =
71 | clazz.declaredMemberProperties.find {
72 | it.name == "prop1" }!!
73 | val f1: KFunction<*> =
74 | clazz.declaredFunctions.find {
75 | it.name == "function" }!!
76 |
77 | //----#### SNIPPET #### - 5
78 | ...
79 | val instance = MyClass(42)
80 |
81 | val p1: KProperty1? =
82 | clazz.declaredMemberProperties.find {
83 | it.name == "prop1" }!!
84 | val p1Mutable: KMutableProperty1 =
85 | p1 as KMutableProperty1
86 |
87 | // getting
88 | val prop1Val = p1.getter.call(instance)
89 |
90 | // setting
91 | p1Mutable.setter.call(instance, 55)
92 |
93 | // invoking
94 | val f1: KFunction<*> =
95 | clazz.declaredFunctions.find {
96 | it.name == "function" }!!
97 | val res = f1.call(instance, 44) as Int
98 |
99 | //----#### SNIPPET #### - 6
100 | // Only directly declared superclasses and interfaces
101 | clazz.superclasses.forEach { sc ->
102 | Log.d("LOG", sc.toString())
103 | }
104 |
105 | // All superclasses and interfaces
106 | clazz.allSuperclasses.forEach { sc ->
107 | Log.d("LOG", sc.toString())
108 | }
109 |
110 | //----#### SNIPPET #### - 7
111 | val clazz : KClass = ...
112 |
113 | // If we have a no-arg primary constructor
114 | val instance1 = clazz.createInstance()
115 |
116 | // Otherwise for the primary constructor
117 | val instance2 = clazz.primaryConstructor?.call(
118 | [parameters]
119 | )
120 |
121 | // Otherwise
122 | val instance3 = clazz.constructors.
123 | find { [criterion] }!!.
124 | call( [parameters] )
125 |
--------------------------------------------------------------------------------
/170/src_chapt17_sect006_Regular_Expressions.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 17:
3 | //// More APIs
4 | //// Section: 6. Regular Expressions
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | val patStr = "^\\w{3}$" // exactly 3 word chars
10 | val patStr2 = """^\w{3}$""" // the same
11 |
12 | //----#### SNIPPET #### - 2
13 | val re = Regex("^\\w{3}$") // exactly 3 word chars
14 |
15 | val matches1 = "Hello".matches(re) // -> false
16 | val matches2 = "abc".matches(re) // -> true
17 |
18 |
19 | //----#### SNIPPET #### - 3
20 | Regex(pattern:String, option:RegexOption)
21 | Regex(pattern:String, options:Set)
22 |
23 | //----#### SNIPPET #### - 4
24 | val re1 = Regex("^A(/|_)\\d{4}$")
25 |
26 | // This is the same:
27 | val ENDS = "$"
28 | val re2 = Regex("""
29 | ^ # begins with
30 | A # an "A"
31 | (/|_) # a "/" or a "_"
32 | \d{4} # 4 digits
33 | $ENDS # ends here
34 | """, RegexOption.COMMENTS)
35 |
36 | //----#### SNIPPET #### - 5
37 | val re = Regex("\\|")
38 | // <- use "\" escape to get a "|" as a literal
39 |
40 | val s = "ABC|12345|_0_1"
41 | val split: List = s.split(re)
42 | // -> "ABC", "12345", "_0_1"
43 |
44 | // limit to at most 37 splits
45 | val split37 = s.split(re, limit = 37)
46 |
47 | //----#### SNIPPET #### - 6
48 | // a number pattern
49 | val re = Regex("""
50 | -? # possibly a "-"
51 | \d+ # one or more digits
52 | (
53 | \. # a dot
54 | \d+ # one or more digits
55 | )? # possibly
56 | """, RegexOption.COMMENTS)
57 |
58 | val s = "x = 37.5, y = 3.14, z = -100.0"
59 |
60 | val firstNumber:MatchResult? = re.find(s)
61 | // start at a certain index instead:
62 | // val firstNumber = re.find(s, 5)
63 |
64 | val notFound = firstNumber == null
65 | firstNumber?.run {
66 | val num = groupValues[0]
67 | // do something with num...
68 | }
69 |
70 | val allNumbers:Sequence = re.findAll(s)
71 | allNumbers.forEach { mr ->
72 | val num = mr.groupValues[0]
73 | // do something with num...
74 | }
75 |
76 | //----#### SNIPPET #### - 7
77 | val re = Regex("""
78 | (
79 | (
80 | -? # possibly a "-"
81 | \d+ # one or more digits
82 | )
83 | (
84 | \. # a dot
85 | (
86 | \d+ # one or more digits
87 | )
88 | )? # possibly
89 | )
90 | """, RegexOption.COMMENTS)
91 |
92 | //----#### SNIPPET #### - 8
93 | // The pattern from the last listing compressed
94 | val re = Regex("""((-?\d+)(\.(\d+))?)""")
95 |
96 | val s = "x = 37.5, y = 3.14, z = -100.0"
97 |
98 | val firstNumber:MatchResult? = re.find(s)
99 |
100 | val notFound = firstNumber == null
101 | firstNumber?.run {
102 | val (num, nf, f1, f2) = destructured
103 | // <- "37.5", "37", ".5", "5"
104 | // the same:
105 | // val num = groupValues[1]
106 | // val nf = groupValues[2]
107 | // val f1 = groupValues[3]
108 | // val f2 = groupValues[4]
109 | val wholeMatch = groupValues[0] // 37.5
110 | // ...
111 | }
112 |
113 | val allNumbers:Sequence = re.findAll(s)
114 | allNumbers.forEach { mr ->
115 | val (num, nf, f1, f2) = mr.destructured
116 | // the same:
117 | // val num = mr.groupValues[1]
118 | // val nf = mr.groupValues[2]
119 | // val f1 = mr.groupValues[3]
120 | // val f2 = mr.groupValues[4]
121 | val wholeMatch = mr.groupValues[0]
122 | // ... wholeMatch is: 37.5, 3.14 or -100.0
123 | // ... num is: 37.5, 3.14 or -100.0
124 | // ... nf is: 37, 3, -100
125 | // ... f1 is: .5, .14, .0
126 | // ... f2 is 5, 14, 0
127 | }
128 |
129 | //----#### SNIPPET #### - 9
130 | // again the number pattern:
131 | val re = Regex("""((-?\d+)(\.(\d+))?)""")
132 |
133 | val s = "x = 37.5, y = 3.14, z = -100.0"
134 |
135 | // replace the first number by 22.22
136 | val s2 = re.replaceFirst(s, "22.22")
137 | // -> "x = 22.22, y = 3.14, z = -100.0"
138 |
139 | // replace all numbers by 22.22
140 | val s3 = re.replace(s, "22.22")
141 | // -> "x = 22.22, y = 22.22, z = 22.22"
142 |
143 | //----#### SNIPPET #### - 10
144 | // again the number pattern:
145 | val re = Regex("""((-?\d+)(\.(\d+))?)""")
146 |
147 | val s = "x = 37.5, y = 3.14, z = -100.0"
148 |
149 | // double all numbers
150 | val s2 = re.replace(s, { mr:MatchResult ->
151 | val theNum = mr.groupValues[1].toDouble()
152 | (theNum * 2).toString() // <- replacement
153 | })
154 | // -> "x = 75.0, y = 6.28, z = -200.0"
155 |
156 | // zero all fractions
157 | val s3 = re.replace(s, { mr:MatchResult ->
158 | val (num, nf, f1, f2) = mr.destructured
159 | nf + ".0" // <- replacement
160 | })
161 | // -> "x = 37.0, y = 3.0, z = -100.0"
162 |
--------------------------------------------------------------------------------
/180/src_chapt18_sect001_Basic_Multithreading_The_Java_Way.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 18:
3 | //// Working in Parallel: Multithreading
4 | //// Section: 1. Basic Multithreading The Java Way
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | fun thread(
10 | start: Boolean = true,
11 | isDaemon: Boolean = false,
12 | contextClassLoader: ClassLoader? = null,
13 | name: String? = null,
14 | priority: Int = -1,
15 | block: () -> Unit
16 | )
17 |
18 | //----#### SNIPPET #### - 2
19 | val thr:Thread = thread(start = true) {
20 | ... do something ...
21 | }
22 |
23 | //----#### SNIPPET #### - 3
24 | // inside an activity:
25 | override fun onCreate(savedInstanceState: Bundle?) {
26 | ...
27 | thread {
28 | while(true) {
29 | Thread.sleep(1000L)
30 | Log.e("LOG", Date().toString())
31 | }
32 | }
33 | }
34 |
35 | //----#### SNIPPET #### - 4
36 | val thr:Thread = thread {
37 | while(true) {
38 | Thread.sleep(1000L)
39 | Log.e("LOG", Date().toString())
40 | }
41 | }
42 |
43 | //----#### SNIPPET #### - 5
44 | val thr = thread(start = false) {
45 | while(true) {
46 | Thread.sleep(1000L)
47 | Log.e("LOG", Date().toString())
48 | }
49 | }
50 | ...
51 | thr.start()
52 |
53 | //----#### SNIPPET #### - 6
54 | val l = mutableListOf(1,2,3)
55 | var i = 0
56 | thread {
57 | while(true) {
58 | Thread.sleep(10L)
59 | i++
60 | if(i % 2 == 0) { l.add(i) }
61 | else { l.remove(l.first()) }
62 | }
63 | }
64 | thread {
65 | while(true) {
66 | Thread.sleep(1000L)
67 | Log.e("LOG", l.joinToString())
68 | }
69 | }
70 |
71 | //----#### SNIPPET #### - 7
72 | val l = mutableListOf(1,2,3)
73 | var i = 0
74 | thread {
75 | while(true) {
76 | Thread.sleep(10L)
77 | i++
78 | synchronized(l) {
79 | if(i % 2 == 0) { l.add(i) }
80 | else { l.remove(l.first()) }
81 | }
82 | }
83 | }
84 | thread {
85 | while(true) {
86 | Thread.sleep(1000L)
87 | synchronized(l) {
88 | Log.e("LOG", l.joinToString())
89 | }
90 | }
91 | }
92 |
93 | //----#### SNIPPET #### - 8
94 | synchronized(l1, l2) {
95 | ...
96 | }
97 |
98 | //----#### SNIPPET #### - 9
99 | val l = mutableListOf(1,2,3)
100 | var i = 0
101 | val thr1 = thread {
102 | for(i in 1..100) {
103 | l.add(i)
104 | Thread.sleep(10)
105 | }
106 | }
107 | thread {
108 | // Here we want to wait until thread thr1 is done.
109 | // How can this be achieved?
110 | ...
111 | Log.e("LOG", l.joinToString())
112 | }
113 |
114 | //----#### SNIPPET #### - 10
115 | val l = mutableListOf(1,2,3)
116 | var i = 0
117 | val thr1 = thread {
118 | ...
119 | }
120 | thread {
121 | thr1.join()
122 | Log.e("LOG", l.joinToString())
123 | }
124 |
--------------------------------------------------------------------------------
/180/src_chapt18_sect002_Advanced_Multithreading_The_Java_Way.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 18:
3 | //// Working in Parallel: Multithreading
4 | //// Section: 2. Advanced Multithreading The Java Way
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | val obj = ...
10 | thread {
11 | synchronized(obj) {
12 | ... synchronized code
13 | }
14 | }
15 |
16 | //----#### SNIPPET #### - 2
17 | import java.util.concurrent.lock.*
18 | ...
19 | val lock:Lock = ...
20 | ...
21 | lock.lock()
22 | try {
23 | ... synchronized code
24 | } finally {
25 | lock.unlock()
26 | }
27 |
28 | //----#### SNIPPET #### - 3
29 | val lock:Lock = ReentrantLock()
30 |
31 | //----#### SNIPPET #### - 4
32 | val lock:Lock = ReentrantLock()
33 | ...
34 | try {
35 | lock.lockInterruptibly()
36 | } catch(e: InterruptedException) {
37 | ... do things if we were interrupted
38 | return
39 | }
40 |
41 | try {
42 | ... synchronized code
43 | } finally {
44 | lock.unlock()
45 | }
46 |
47 | //----#### SNIPPET #### - 5
48 | val lock:Lock = ReentrantLock()
49 | ...
50 | if(lock.tryLock()) {
51 | try {
52 | ... synchronized code
53 | } finally {
54 | lock.unlock()
55 | }
56 | } else {
57 | ... no lock acquired
58 | ... do other things
59 | }
60 |
61 | //----#### SNIPPET #### - 6
62 | ...
63 | if(lock.tryLock(time:Long, unit:TimeUnit)) {
64 | // lock was acquired within that time span
65 | ...
66 | } else {
67 | ...
68 | }
69 |
70 | //----#### SNIPPET #### - 7
71 | class Counter {
72 | var c = 0
73 | fun increment() { c++ }
74 | fun decrement() { c-- }
75 | }
76 |
77 | //----#### SNIPPET #### - 8
78 | class Counter {
79 | var c = 0
80 | fun increment() { synchronized(c){ c++ } }
81 | fun decrement() { synchronized(c){ c-- } }
82 | }
83 |
84 | //----#### SNIPPET #### - 9
85 | import java.util.concurrent.atomic.*
86 | ...
87 | class Counter {
88 | var c:AtomicInteger = AtomicInteger(0)
89 | fun increment() { c.incrementAndGet() }
90 | fun decrement() { c.decrementAndGet() }
91 | }
92 |
93 | //----#### SNIPPET #### - 10
94 | class MainActivity : AppCompatActivity() {
95 | var points = 0L
96 | var insideCircle = 0L
97 | var totalIters = 0L
98 |
99 | override
100 | fun onCreate(savedInstanceState: Bundle?) {
101 | super.onCreate(savedInstanceState)
102 | setContentView(R.layout.activity_main)
103 |
104 | savedInstanceState?.run {
105 | points = getLong("points")
106 | insideCircle = getLong("insideCircle")
107 | totalIters = getLong("totalIter")
108 | }
109 |
110 | val cores = Runtime.getRuntime().
111 | availableProcessors()
112 | procs.setText(cores.toString())
113 | }
114 |
115 | override
116 | fun onSaveInstanceState(outState: Bundle?) {
117 | super.onSaveInstanceState(outState)
118 | outState?.run {
119 | putLong("points",points)
120 | putLong("insideCircle",insideCircle)
121 | putLong("totalIter", totalIters)
122 | report()
123 | }
124 | }
125 |
126 | fun calc(v:View) {
127 | val t1 = System.currentTimeMillis()
128 | val nThreads = threads.text.toString().
129 | takeIf { it != "" }?.toInt()?:1
130 | val itersNum = iters.text.toString().
131 | takeIf { it != "" }?.toInt()?:10000
132 | val itersPerThread = itersNum / nThreads
133 | val srvc = Executors.newFixedThreadPool(nThreads)
134 | val callables = (1..nThreads).map {
135 | object : Callable> {
136 | override fun call(): Pair {
137 | var i = 0
138 | var p = 0
139 | (1..itersPerThread).forEach {
140 | val x = Math.random()
141 | val y = Math.random()
142 | val r = x*x + y*y
143 | i++
144 | if(r < 1.0) p++
145 | }
146 | return Pair(i, p)
147 | }
148 | }
149 | }
150 | val futures = srvc.invokeAll(callables)
151 | futures.forEach{ f ->
152 | val p = f.get()
153 | points += p.first
154 | insideCircle += p.second
155 | }
156 |
157 | val t2 = System.currentTimeMillis()
158 | calcTime.setText((t2-t1).toString())
159 |
160 | report()
161 | }
162 |
163 | fun reset(v:View) {
164 | points = 0
165 | insideCircle = 0
166 | report()
167 | }
168 |
169 | private fun report() {
170 | cumulIters.setText(points.toString())
171 | if(points > 0) {
172 | val pipi = 1.0 * insideCircle / points * 4
173 | pi.setText(pipi.toString())
174 | } else {
175 | pi.setText("")
176 | }
177 | }
178 | }
179 |
--------------------------------------------------------------------------------
/180/src_chapt18_sect003_Kotlin_Coroutines.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 18:
3 | //// Working in Parallel: Multithreading
4 | //// Section: 3. Kotlin Coroutines
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | class MyActivity : AppCompatActivity(),
10 | CoroutineScope by MainScope() {
11 | ...
12 | override fun onDestroy() {
13 | super.onDestroy()
14 | cancel() // CoroutineScope.cancel
15 | }
16 | ...
17 | }
18 |
19 | //----#### SNIPPET #### - 2
20 | withTimeout(3000L) { // milliseconds
21 | ... code here
22 | }
23 |
24 | //----#### SNIPPET #### - 3
25 | val res = withTimeoutOrNull(3000L) {
26 | ... code here
27 | "Done."
28 | }
29 | // -> res is null if timeout happened
30 |
31 | //----#### SNIPPET #### - 4
32 | runBlocking {
33 | val job = launch {
34 | try {
35 | ... do work
36 | } finally {
37 | ... cleanup if canceled
38 | }
39 | }
40 | ...
41 | job.cancelAndJoin()
42 | }
43 |
44 | //----#### SNIPPET #### - 5
45 | runBlocking {
46 | ...
47 | }
48 |
49 | //----#### SNIPPET #### - 6
50 | runBlocking {
51 | val ctx:CoroutineContext =
52 | coroutineContext
53 | ...
54 | }
55 |
56 | //----#### SNIPPET #### - 7
57 | openScope {
58 | // Scope now automatically available
59 | ...
60 | }
61 |
62 | //----#### SNIPPET #### - 8
63 | fun runBlocking(context: CoroutineContext =
64 | EmptyCoroutineContext,
65 | block: suspend CoroutineScope.() -> T): T
66 | {
67 | // code to run block in a blocking thread
68 | ...
69 | }
70 |
71 | //----#### SNIPPET #### - 9
72 | public fun CoroutineScope.launch(
73 | context: CoroutineContext = EmptyCoroutineContext,
74 | start: CoroutineStart = CoroutineStart.DEFAULT,
75 | block: suspend CoroutineScope.() -> Unit
76 | ): Job
77 |
78 | //----#### SNIPPET #### - 10
79 | launch(context = coroutineContext +
80 | CoroutineName("CoRou1")) {
81 | ....
82 | )
83 |
84 | //----#### SNIPPET #### - 11
85 | runBlocking {
86 | // This starts in the current thread.
87 | // We are now inside a coroutine scope. This means
88 | // we have a
89 | // val coroutineContext:CoroutineContext
90 | // for the context. The runBlocking() ends
91 | // after all work is done.
92 | Log.d("LOG", "1. Started inside runBlocking()")
93 |
94 | coroutineScope {
95 | Log.d("LOG", "2. coroutineScope()")
96 | delay(500L)
97 | Log.d("LOG", "3. coroutineScope()")
98 |
99 | coroutineScope {
100 | Log.d("LOG", "4. coroutineScope() II")
101 | // If you add this, both coroutineScope()
102 | // fail and runBlocking() prematurely ends:
103 | // throw CancellationException("4.")
104 |
105 | // Also, because runBlocking transports the
106 | // exception to the outside world, (15.)
107 | // below will not be reached.
108 | }
109 | Log.d("LOG", "5. inner done")
110 | }
111 |
112 | val job1 = launch {
113 | // This runs in the background, so
114 | // (8.) happens before (7.)
115 | Log.d("LOG", "6. inside launch()")
116 | delay(500)
117 | Log.d("LOG", "7. done with launch()")
118 | }
119 | Log.d("LOG", "8. returned from launch()")
120 |
121 | val deferr1 = async {
122 | // This runs in the background as well, but it
123 | // returns something
124 | Log.d("LOG", "9. inside async()")
125 | delay(500)
126 | Log.d("LOG", "10. done with async()")
127 | "Result"
128 | }
129 | Log.d("LOG", "11. returned from async()")
130 |
131 | job1.join()
132 | Log.d("LOG", "12. launch finish")
133 |
134 | val res1 = deferr1.await()
135 | Log.d("LOG", "13. async finish")
136 |
137 | Log.d("LOG", "14. End of runBlocking()")
138 | }
139 | Log.d("LOG", "15. Returned from runBlocking()")
140 |
141 | //----#### SNIPPET #### - 12
142 | withContext(context: CoroutineContext) {
143 | ...
144 | }
145 |
146 | //----#### SNIPPET #### - 13
147 | ... we are inside a coroutine scope
148 |
149 | withContext(context = coroutineContext +
150 | CoroutineName("TmpName")) {
151 | ... here we have a scope with a tweaked context
152 | }
153 |
154 | //----#### SNIPPET #### - 14
155 | runBlocking {
156 | ...
157 | launch {
158 | ...
159 | }
160 | }
161 |
162 | //----#### SNIPPET #### - 15
163 | runBlocking {
164 | ...
165 | doLaunch()
166 | }
167 |
168 | suspend fun doLaunch() {
169 | launch {
170 | ...
171 | }
172 | }
173 |
174 | //----#### SNIPPET #### - 16
175 | val job = launch { ... }
176 | val deferr = async { ... }
177 |
178 | job.join() // suspend until job finished
179 | deferr.join() // suspend until deferr finished
180 |
181 | //----#### SNIPPET #### - 17
182 | val deferr1 = async { ... }
183 | val deferr2 = async { ... }
184 |
185 | val deferr1Res = deferr1.await()
186 | val deferr2Res = deferr2.await()
187 |
188 | //----#### SNIPPET #### - 18
189 | val deferr1Res = deferr1.getCompleted()
190 |
191 | //----#### SNIPPET #### - 19
192 | runBlocking {
193 | val job1 = launch {
194 | }
195 | job1.join() // unnecessary!
196 | }
197 |
198 | //----#### SNIPPET #### - 20
199 | val job = launch { ... }
200 | val deferr = async { ... }
201 | ...
202 | job.cancel() // or deferr.cancel()
203 |
204 | //----#### SNIPPET #### - 21
205 | val job = launch { ... }
206 | ...
207 | job.cancel()
208 | job.join()
209 |
210 | //----#### SNIPPET #### - 22
211 | val job = launch { ... }
212 | ...
213 | job.cancelAndJoin()
214 |
215 | //----#### SNIPPET #### - 23
216 | withTimeout(1000L) { // milliseconds
217 | ...
218 | }
219 |
220 | //----#### SNIPPET #### - 24
221 | val res = withTimeoutOrNull(1000L) { // milliseconds
222 | ...
223 | [result expression]
224 | }
225 |
226 | //----#### SNIPPET #### - 25
227 | withTimeoutOrNull(1000L) { // milliseconds
228 | ...
229 | "OK"
230 | } ?: throw Exception("Timeout Exception")
231 |
232 | //----#### SNIPPET #### - 26
233 | coroutineContext[ContinuationInterceptor]
234 |
235 | //----#### SNIPPET #### - 27
236 | val myDispatcher = ...
237 | runBlocking {
238 | val job = launch(coroutineContext + myDispatcher) {
239 | ...
240 | }
241 | job.join()
242 | }
243 |
244 | //----#### SNIPPET #### - 28
245 | class MyClass :
246 | CoroutineScope by MainScope()
247 | {
248 | ...
249 | }
250 |
251 | //----#### SNIPPET #### - 29
252 | var l1:Job? = null
253 | var l11:Job? = null
254 | var l111:Job? = null
255 | runBlocking {
256 | Log.d("LOG", "A")
257 | l1 = launch {
258 | Log.d("LOG", "B")
259 | l11 = launch {
260 | Log.d("LOG", "C")
261 | delay(1000L)
262 | Log.d("LOG", "D")
263 | l111 = launch {
264 | Log.d("LOG", "E")
265 | delay(1000L)
266 | Log.d("LOG", "F")
267 | delay(1000L)
268 | Log.d("LOG", "G")
269 | }
270 | delay(2500L)
271 | Log.d("LOG", "H")
272 | }
273 | delay(1000L)
274 | Log.d("LOG", "I")
275 | }
276 |
277 | Log.d("LOG", "X1")
278 | delay(1500L)
279 | Log.d("LOG", "X2")
280 | l111?.cancel()
281 | Log.d("LOG", "X3")
282 | }
283 |
284 | //----#### SNIPPET #### - 30
285 | ...
286 | withContext(NonCancellable) {
287 | // uncancellable code here
288 | ...
289 | }
290 | ...
291 |
292 | //----#### SNIPPET #### - 31
293 | val handler = CoroutineExceptionHandler {
294 | _, exception ->
295 | Log.e("LOG", "Caught $exception")
296 | }
297 |
298 | runBlocking(handler) {
299 | ...
300 | }
301 |
302 | //----#### SNIPPET #### - 32
303 | val handler = ...
304 | runBlocking {
305 | ...
306 | launch(coroutineContext + handler) {
307 | ...
308 | }
309 | }
310 |
311 | //----#### SNIPPET #### - 33
312 | // we are inside a coroutine scope
313 |
314 | val supervisor = SupervisorJob()
315 | withContext(coroutineContext + supervisor) {
316 | // the coroutines hierarchy here
317 | ...
318 | }
319 |
320 | //----#### SNIPPET #### - 34
321 | // we are inside a coroutine scope
322 |
323 | supervisorScope {
324 | // the coroutines hierarchy here
325 | ...
326 | }
327 |
--------------------------------------------------------------------------------
/190/src_chapt19_sect001_Adding_External_Libraries.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 19:
3 | //// Using External Libraries
4 | //// Section: 1. Adding External Libraries
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 |
11 |
12 | org.apache.commons
13 | commons-math3
14 | 3.2
15 |
16 |
--------------------------------------------------------------------------------
/190/src_chapt19_sect004_External_Libraries_And_Nullability.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 19:
3 | //// Using External Libraries
4 | //// Section: 4. External Libraries And Nullability
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | val res = javaObject.function() ?:
10 | throw Exception("Cannot happen")
11 |
--------------------------------------------------------------------------------
/190/src_chapt19_sect005_Creating_Your_Own_Library.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 19:
3 | //// Using External Libraries
4 | //// Section: 5. Creating Your Own Library
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | val s = "The big brown fox jumps over the creek."
10 | val containsOnlyLetters = s % "[A-Za-z ]*"
11 | // -> false because of the "."
12 |
13 | //----#### SNIPPET #### - 2
14 | package org.foo.stringregex
15 |
16 | operator fun String.rem(re:String):Boolean =
17 | this.matches(Regex(re))
18 |
19 | //----#### SNIPPET #### - 3
20 | import org.foo.stringregex.rem
21 |
22 | ...
23 | val s = "The big brown fox jumps over the creek."
24 | val containsOnlyLetters = s % "[A-Za-z ]*"
25 | // -> false because of the "."
26 |
--------------------------------------------------------------------------------
/200/src_chapt20_sect001_XML_Processing.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 20:
3 | //// XML And JSON
4 | //// Section: 1. XML Processing
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 |
10 |
11 | 2016-10-30T19:07:07Z
12 | 1A6G
13 | 37.4
14 |
15 | 045
16 | -3
17 | P. Rosengaard
18 |
19 |
20 |
21 | //----#### SNIPPET #### - 2
22 | package com.example.domext
23 |
24 | import org.apache.xerces.parsers.DOMParser
25 | import org.w3c.dom.Document
26 | import org.w3c.dom.Node
27 | import org.xml.sax.InputSource
28 | import java.io.StringReader
29 | import java.io.StringWriter
30 | import javax.xml.transform.OutputKeys
31 | import javax.xml.transform.TransformerFactory
32 | import javax.xml.transform.dom.DOMSource
33 | import javax.xml.transform.stream.StreamResult
34 |
35 | fun parseXmlToDOM(s:String) : Document {
36 | val parser: DOMParser = DOMParser()
37 | return parser.let {
38 | it.parse(InputSource(StringReader(s)))
39 | it.document
40 | }
41 | }
42 |
43 | fun Node.fetchChildren(withText:Boolean = false) =
44 | (0..(this.childNodes.length - 1)).
45 | map { this.childNodes.item(it) }.
46 | filter { withText || it.nodeType != Node.TEXT_NODE }
47 |
48 | fun Node.childCount() = fetchChildren().count()
49 |
50 | fun Node.forEach(withText:Boolean = false,
51 | f:(Node) -> Unit) {
52 | fetchChildren(withText).forEach { f(it) }
53 | }
54 |
55 | operator fun Node.get(i:Int) = fetchChildren()[i]
56 |
57 | operator fun Node.invoke(s:String): Node =
58 | if(s.startsWith("@")) {
59 | this.attributes.getNamedItem(s.substring(1))
60 | }else{
61 | this.childNodes.let { nl ->
62 | val iter = object : Iterator {
63 | var i: Int = 0
64 | override fun next() = nl.item(i++)
65 | override fun hasNext() = i < nl.length
66 | }
67 | iter.asSequence().find { it.nodeName == s }!!
68 | }
69 | }
70 |
71 | operator fun Node.invoke(vararg s:String): Node =
72 | s.fold(this, { acc, s1 -> acc(s1) })
73 |
74 | fun Node.text() = this.firstChild.nodeValue
75 | fun Node.name() = this.nodeName
76 | fun Node.type() = this.nodeType
77 |
78 | //----#### SNIPPET #### - 3
79 | import ...
80 | import com.example.domext.*
81 |
82 | ...
83 | val xml = """
84 |
85 | 2016-10-30T19:07:07Z
86 | 1A6G
87 | 37.4
88 |
89 | 045
90 | -3
91 | P. Rosengaard
92 |
93 | """
94 |
95 |
96 | try {
97 | // Parse the complete XML document
98 | val dom = parseXmlToDOM(xml)
99 |
100 | // Access an element
101 | val ts = dom("ProbeMsg")("TimeStamp").text()
102 | Log.d("LOG", ts) // 2001-11-30T09:08:07Z
103 |
104 | // Access an attribute
105 | val uni = dom("ProbeMsg")("ProbeValue")("@ScaleUnit")
106 | Log.d("LOG", uni.text()) // cm
107 |
108 | // Simplified XML tree navigation
109 | val uni2 = dom("ProbeMsg","ProbeValue","@ScaleUnit")
110 | Log.d("LOG", uni2.text()) // cm
111 |
112 | // Iterate through an element's children
113 | dom("ProbeMsg")("Meta").forEach { n ->
114 | Log.d("LOG", n.name() + ": " + n.text())
115 | // Generator: 045
116 | // Priority: -3
117 | // Actor: P. Rosengaard
118 | }
119 | }catch(e:Exception) {
120 | Log.e("LOG", "Cannot parse XML", e)
121 | }
122 | ...
123 |
124 | //----#### SNIPPET #### - 4
125 | fun prettyFormatXml(document:Document): String {
126 | val format = OutputFormat(document).apply {
127 | lineWidth = 65
128 | indenting = true
129 | indent = 2
130 | }
131 | val out = StringWriter()
132 | val serializer = XMLSerializer(out, format)
133 | serializer.serialize(document)
134 | return out.toString()
135 | }
136 |
137 | fun prettyFormatXml(unformattedXml: String) =
138 | prettyFormatXml(parseXmlToDOM(unformattedXml))
139 |
140 | fun Node.toXmlString():String {
141 | val transformerFact = TransformerFactory.newInstance()
142 | val transformer = transformerFact.newTransformer()
143 | transformer.setOutputProperty(OutputKeys.INDENT, "yes")
144 | val source = DOMSource(this)
145 | val writer = StringWriter()
146 | val result = StreamResult(writer)
147 | transformer.transform(source, result)
148 | return writer.toString()
149 | }
150 |
151 | operator fun Node.plusAssign(child:Node) {
152 | this.appendChild(child)
153 | }
154 |
155 | fun Node.addText(s:String): Node {
156 | val doc = ownerDocument
157 | val txt = doc.createTextNode(s)
158 | appendChild(txt)
159 | return this
160 | }
161 |
162 | fun Node.removeText() {
163 | if(hasChildNodes() &&
164 | firstChild.nodeType == Node.TEXT_NODE)
165 | removeChild(firstChild)
166 | }
167 |
168 | fun Node.updateText(s:String) : Node {
169 | removeText()
170 | return addText(s)
171 | }
172 |
173 | fun Node.addAttribute(name:String, value:String): Node {
174 | (this as Element).setAttribute(name, value)
175 | return this
176 | }
177 |
178 | fun Node.removeAttribute(name:String) {
179 | this.attributes.removeNamedItem(name)
180 | }
181 |
182 | //----#### SNIPPET #### - 5
183 | val xml = """
184 |
185 | 2016-10-30T19:07:07Z
186 | 1A6G
187 | 37.4
188 |
189 | 045
190 | -3
191 | P. Rosengaard
192 |
193 | """
194 |
195 | try {
196 | val dom = parseXmlToDOM(xml)
197 |
198 | val msg = dom("ProbeMsg")
199 | val meta = msg("Meta")
200 |
201 | // Add a new element to "meta".
202 | meta += dom.createElement("NewMeta").
203 | addText("NewValue").
204 | addAttribute("SomeAttr", "AttrVal")
205 |
206 | Log.d("LOG", "\n\n" + prettyFormatXml(dom))
207 |
208 | }catch(e:Exception) {
209 | Log.e("LOG", "XML Error", e)
210 | }
211 |
212 | //----#### SNIPPET #### - 6
213 | val xml = """
214 |
215 | 2016-10-30T19:07:07Z
216 | 1A6G
217 | 37.4
218 |
219 | 045
220 | -3
221 | P. Rosengaard
222 |
223 | """
224 |
225 | try {
226 | val dom = parseXmlToDOM(xml)
227 |
228 | val msg = dom("ProbeMsg")
229 | val ts = msg("TimeStamp")
230 | val probeValue = msg("ProbeValue")
231 |
232 | // Update an attribute and the text contents of
233 | // an element.
234 | probeValue.updateAttribute("ScaleUnit", "dm")
235 | ts.updateText("1970-01-01T00:00:00Z")
236 | Log.d("LOG", "\n\n" + prettyFormatXml(dom))
237 |
238 | // Remove an attribute
239 | probeValue.removeAttribute("ScaleUnit")
240 | Log.d("LOG", "\n\n" + prettyFormatXml(dom))
241 |
242 | // Removing a node means removing it from
243 | // its parent node.
244 | msg.removeChild(probeValue)
245 | Log.d("LOG", "\n\n" + prettyFormatXml(dom))
246 |
247 | }catch(e:Exception) {
248 | Log.e("LOG", "XML Error", e)
249 | }
250 |
251 | //----#### SNIPPET #### - 7
252 | val doc = DocumentBuilderFactory.
253 | newInstance().newDocumentBuilder().newDocument()
254 |
--------------------------------------------------------------------------------
/200/src_chapt20_sect002_JSON_Processing.txt:
--------------------------------------------------------------------------------
1 | //// ------------------------------------------------------
2 | //// Snippets from chapter 20:
3 | //// XML And JSON
4 | //// Section: 2. JSON Processing
5 | //// ------------------------------------------------------
6 |
7 |
8 | //----#### SNIPPET #### - 1
9 | val json = """{
10 | "id":27,
11 | "name":"Roger Rabbit",
12 | "permanent":true,
13 | "address":{
14 | "street":"El Camino Real",
15 | "city":"New York",
16 | "zipcode":95014
17 | },
18 | "phoneNumbers":[9945678, 123456781],
19 | "role":"President"
20 | }"""
21 |
22 | //----#### SNIPPET #### - 2
23 | import com.fasterxml.jackson.core.JsonFactory
24 | import com.fasterxml.jackson.core.util.DefaultPrettyPrinter
25 | import com.fasterxml.jackson.databind.JsonNode
26 | import com.fasterxml.jackson.databind.ObjectMapper
27 | import com.fasterxml.jackson.databind.node.*
28 | import java.io.ByteArrayOutputStream
29 | import java.math.BigInteger
30 |
31 | operator fun JsonNode.invoke(s:String) = this.get(s)
32 | operator fun JsonNode.invoke(vararg s:String) =
33 | s.fold(this, { acc, s -> acc(s) })
34 | fun JsonNode.remove(name:String) {
35 | val on = (this as? ObjectNode)?:
36 | throw Exception("This is not an object node")
37 | on.remove(name) }
38 | fun JsonNode.forEach(iter: (JsonNode) -> Unit ) {
39 | when(this) {
40 | is ArrayNode -> this.forEach(iter)
41 | is ObjectNode -> this.forEach(iter)
42 | else -> throw Exception("Cannot iterate over " +
43 | this::class)
44 | }
45 | }
46 |
47 | //----#### SNIPPET #### - 3
48 | fun JsonNode.text() = this.asText()
49 |
50 | //----#### SNIPPET #### - 4
51 | fun JsonNode.forEach(iter: (String, JsonNode) -> Unit ) {
52 | if(this !is ObjectNode)
53 | throw Exception(
54 | "Cannot iterate (key,val) over " + this::class)
55 | this.fields().forEach{
56 | (name, value) -> iter(name, value) }
57 | }
58 |
59 | //----#### SNIPPET #### - 5
60 | // Works only if the node is an ObjectNode!
61 | fun JsonNode.put(name:String, value:Any?) : JsonNode {
62 | if(this !is ObjectNode)
63 | throw Exception("Cannot put() on none-object node")
64 | when(value) {
65 | null -> this.putNull(name)
66 | is Int -> this.put(name, value)
67 | is Long -> this.put(name, value)
68 | is Short -> this.put(name, value)
69 | is Float -> this.put(name, value)
70 | is Double -> this.put(name, value)
71 | is Boolean -> this.put(name, value)
72 | is String -> this.put(name, value)
73 | is JsonNode -> this.put(name, value)
74 | else -> throw Exception(
75 | "Illegal value type: ${value::class}")
76 | }
77 | return this
78 | }
79 |
80 | //----#### SNIPPET #### - 6
81 | // Add a value to an array, works only if this is an
82 | // ArrayNode
83 | fun JsonNode.add(value:Any?) : JsonNode {
84 | if(this !is ArrayNode)
85 | throw Exception("Cannot add() on none-array node")
86 | when(value) {
87 | null -> this.addNull()
88 | is Int -> this.add(value)
89 | is Long -> this.add(value)
90 | is Float -> this.add(value)
91 | is Double -> this.add(value)
92 | is Boolean -> this.add(value)
93 | is String -> this.add(value)
94 | is JsonNode -> this.add(value)
95 | else -> throw Exception(
96 | "Illegal value type: ${value::class}")
97 | }
98 | return this
99 | }
100 |
101 | //----#### SNIPPET #### - 7
102 | // Node creators
103 | fun createJsonTextNode(text:String) =
104 | TextNode.valueOf(text)
105 | fun createJsonIntNode(i:Int) = IntNode.valueOf(i)
106 | fun createJsonLongNode(l:Long) = LongNode.valueOf(l)
107 | fun createJsonShortNode(s:Short) = ShortNode.valueOf(s)
108 | fun createJsonFloatNode(f:Float) = FloatNode.valueOf(f)
109 | fun createJsonDoubleNode(d:Double) = DoubleNode.valueOf(d)
110 | fun createJsonBooleanNode(b:Boolean) =
111 | BooleanNode.valueOf(b)
112 | fun createJsonBigIntegerNode(b: BigInteger) =
113 | BigIntegerNode.valueOf(b)
114 | fun createJsonNullNode() = NullNode.instance
115 |
116 | fun jsonObjectNodeOf(
117 | children: Map = HashMap()) :
118 | ObjectNode {
119 | return ObjectNode(JsonNodeFactory.instance, children)
120 | }
121 | fun jsonObjectNodeOf(
122 | vararg children: Pair) :
123 | ObjectNode {
124 | return children.fold(
125 | ObjectNode(JsonNodeFactory.instance), { acc, v ->
126 | acc.put(v.first, v.second)
127 | acc
128 | })
129 | }
130 | fun jsonArrayNodeOf(elements: Array =
131 | emptyArray()) : ArrayNode {
132 | return ArrayNode(JsonNodeFactory.instance,
133 | elements.asList())
134 | }
135 | fun jsonArrayNodeOf(elements: List =
136 | emptyList()) : ArrayNode {
137 | return ArrayNode(JsonNodeFactory.instance,
138 | elements)
139 | }
140 | fun jsonEmptyArrayNode() : ArrayNode {
141 | return ArrayNode(JsonNodeFactory.instance)
142 | }
143 | fun jsonArrayNodeOf(vararg elements: Any?) : ArrayNode {
144 | return elements.fold(
145 | ArrayNode(JsonNodeFactory.instance), { acc, v ->
146 | acc.add(v)
147 | acc
148 | })
149 | }
150 |
151 | //----#### SNIPPET #### - 8
152 | // JSON output as pretty string
153 | fun JsonNode.toPrettyString(
154 | prettyPrinter:PrettyPrinter? =
155 | DefaultPrettyPrinter()) : String {
156 | var res:String? = null
157 | ByteArrayOutputStream().use { os ->
158 | val gen = JsonFactory().createGenerator(os).apply {
159 | if(prettyPrinter != null) this.prettyPrinter = prettyPrinter
160 | }
161 | val mapper = ObjectMapper()
162 | mapper.writeTree(gen, this)
163 | res = String(os.toByteArray())
164 | }
165 | return res!!
166 | }
167 |
168 | // JSON output as simple string
169 | fun JsonNode.toJsonString() : String =
170 | toPrettyString(prettyPrinter = null)
171 |
172 | //----#### SNIPPET #### - 9
173 | val json = ... // see section beginning
174 | val mapper = ObjectMapper()
175 | val root = mapper.readTree(json)
176 |
177 | //----#### SNIPPET #### - 10
178 | try {
179 | val json = ... // see section beginning
180 | val mapper = ObjectMapper()
181 | val root = mapper.readTree(json)
182 |
183 | // see what we got
184 | Log.d("LOG", root.toPrettyString())
185 |
186 | // type of the node
187 | Log.d("LOG", root.nodeType.toString())
188 | // <- OBJECT
189 | // is it a container?
190 | Log.d("LOG", root.isContainerNode.toString())
191 | // <- true
192 |
193 | root.forEach { k,v ->
194 | Log.d("LOG",
195 | "Key:${k} -> val:${v} (${v.nodeType})")
196 | Log.d("LOG",
197 | " <- " + v::class.toString())
198 | }
199 |
200 | val phones = root("phoneNumbers")
201 | phones.forEach { ph ->
202 | Log.d("LOG", "Phone: " + ph.text())
203 | }
204 | Log.d("LOG", "Phone[0]: " + phones[0].text())
205 |
206 | val street = root("address")("street").text()
207 | Log.d("LOG", "Street: " +
208 | street)
209 | Log.d("LOG", "Zip: " +
210 | root("address", "zipcode").asInt())
211 |
212 | }catch(e:Exception) {
213 | Log.e("LOG", "JSON error", e)
214 | }
215 |
216 | //----#### SNIPPET #### - 11
217 | // add it to the "try" statements from the
218 | // last listing
219 |
220 | // remove an entry
221 | root("address").remove("zipcode")
222 | Log.d("LOG", root.toPrettyString())
223 |
224 | // update an entry
225 | root("address").put("street", "Fake Street 42")
226 | Log.d("LOG", root.toPrettyString())
227 |
228 | root("address").put("country", createJsonTextNode("Argentina"))
229 | Log.d("LOG", root.toPrettyString())
230 |
231 | // create a new object node
232 | root.put("obj", jsonObjectNodeOf(
233 | "abc1" to 23,
234 | "abc2" to "Hallo",
235 | "someNull" to null
236 | ))
237 | Log.d("LOG", root.toPrettyString())
238 |
239 | // create a new array node
240 | root.put("arr", jsonArrayNodeOf(
241 | 23,
242 | null,
243 | "Hallo"
244 | ))
245 | Log.d("LOG", root.toPrettyString())
246 |
247 | // write without spaces or line breaks
248 | Log.d("LOG", root.toJsonString())
249 |
250 | //----#### SNIPPET #### - 12
251 | val root = jsonObjectNodeOf()
252 |
--------------------------------------------------------------------------------
/9781484244661.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Apress/learn-kotlin-for-android-development/ec879594914d4225cff0b5da553356801a5a8dd7/9781484244661.jpg
--------------------------------------------------------------------------------
/Contributing.md:
--------------------------------------------------------------------------------
1 | # Contributing to Apress Source Code
2 |
3 | Copyright for Apress source code belongs to the author(s). However, under fair use you are encouraged to fork and contribute minor corrections and updates for the benefit of the author(s) and other readers.
4 |
5 | ## How to Contribute
6 |
7 | 1. Make sure you have a GitHub account.
8 | 2. Fork the repository for the relevant book.
9 | 3. Create a new branch on which to make your change, e.g.
10 | `git checkout -b my_code_contribution`
11 | 4. Commit your change. Include a commit message describing the correction. Please note that if your commit message is not clear, the correction will not be accepted.
12 | 5. Submit a pull request.
13 |
14 | Thank you for your contribution!
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | Freeware License, some rights reserved
2 |
3 | Copyright (c) 2019 Peter Späth
4 |
5 | Permission is hereby granted, free of charge, to anyone obtaining a copy
6 | of this software and associated documentation files (the "Software"),
7 | to work with the Software within the limits of freeware distribution and fair use.
8 | This includes the rights to use, copy, and modify the Software for personal use.
9 | Users are also allowed and encouraged to submit corrections and modifications
10 | to the Software for the benefit of other users.
11 |
12 | It is not allowed to reuse, modify, or redistribute the Software for
13 | commercial use in any way, or for a user’s educational materials such as books
14 | or blog articles without prior permission from the copyright holder.
15 |
16 | The above copyright notice and this permission notice need to be included
17 | in all copies or substantial portions of the software.
18 |
19 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 | AUTHORS OR COPYRIGHT HOLDERS OR APRESS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25 | SOFTWARE.
26 |
27 |
28 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Apress/learn-kotlin-for-android-development/ec879594914d4225cff0b5da553356801a5a8dd7/README.md
--------------------------------------------------------------------------------
/errata.md:
--------------------------------------------------------------------------------
1 | # Errata for *Book Title*
2 |
3 | On **page xx** [Summary of error]:
4 |
5 | Details of error here. Highlight key pieces in **bold**.
6 |
7 | ***
8 |
9 | On **page xx** [Summary of error]:
10 |
11 | Details of error here. Highlight key pieces in **bold**.
12 |
13 | ***
--------------------------------------------------------------------------------