Skip to content

Commit 232eb65

Browse files
committed
Added some more structure/cleanup and such
1 parent 583f262 commit 232eb65

File tree

3 files changed

+102
-16
lines changed

3 files changed

+102
-16
lines changed

src/main/kotlin/me/kotlindemo/01_IntroToKotlin.kt

+58-9
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package me.kotlindemo
22

3+
import me.kotlindemo.classes.Person
34
import java.lang.NumberFormatException
45
import kotlin.IllegalArgumentException
56

@@ -21,7 +22,10 @@ fun main() {
2122
/**
2223
* FUNCTIONS
2324
* Functions in kotlin are 'first class objects', ie the can be assigned to variables, passed as params
24-
* to other functions, and returned as a result from higher order functions.
25+
* to other functions, and returned as a result from higher order functions. They do not need to be defined
26+
* in a class scope.
27+
*
28+
* expression body vs
2529
*/
2630
fun functions() {
2731
println("\n>>>>> Some functions")
@@ -40,7 +44,7 @@ fun functions() {
4044
}
4145

4246
//functions are first class and do not need to be part of a class
43-
//expression body syntax, return type is inferred. single line only (no {})
47+
//this is expression body syntax, return type is inferred. single line only (no {})
4448
fun add(a: Int, b: Int) = a + b
4549

4650
//return type is required when using {}, multiline
@@ -51,28 +55,27 @@ fun addWithBody(a: Int, b: Int): Int {
5155
//no return type, //implicitly returns Unit
5256
fun addAndPrint(a: Int, b: Int) = println(" fun with expression body: printing sum: ${a + b}")
5357

54-
58+
//return type not needing to be specified, so it's implicit Unit
5559
fun addAndPrintBody(a: Int, b: Int) {
5660
println("\n fun with block body: printing from a body with no return: ${a + b}")
5761
return Unit //not required, can be ignored
5862
}
5963

6064
fun paramsWithDefaultValues(one: String = "blah", two: Boolean = false, three: Int = 0,
61-
fourNullable: String? = null){ //one, two, three are not nullable. four is
65+
fourNullable: String? = null) { //one, two, three are not nullable. four is
6266
println("\n fun params with default values: one: $one two:$two three: $three, fourNullable: $fourNullable")
6367
}
6468

6569
/**
6670
* Lambdas
67-
* Similar to the way java does them for the most part
71+
* Similar to the way java does them for the most part, with a bit less verbage
6872
*/
69-
//Lambda Expressions
7073
//return type is inferred, ie we don't explicitly say 'Int'
7174
val sumTypeInferred = {x: Int, y: Int -> x + y}
7275
val aResult = sumTypeInferred(3, 4)
7376

7477
//Explicit type declaration
75-
// Format: (input params) -> return type = implementation
78+
// Format: (input params) -> return type = {implementation}
7679
val printNumber : (Int) -> Unit = {num -> println(" explioct type declared for lambda num: $num")}
7780
// the following doesn't work even tho I found lots of examples with it
7881
//val printNumberErrors : Int -> Unit = {num -> println(" explioct type declared for lambda num: $num")}
@@ -82,16 +85,27 @@ fun doSomethngWithLambdas() {
8285
println(" invoke a lambdaExpression 3 + 4 = ${sumTypeInferred(3, 4)}")//need ${} since params, even tho it is a 'property'
8386
printNumber(14)
8487
}
88+
8589
/**
8690
* VARIABLES
91+
* types do not need to be specified, they can be determined at time of assignment. You can explicitly define types tho
92+
* once a type has been set, it can't be chanved, ie a val/var set to a string cannot be assigned to an int
93+
* everything is an object, and properties are references
94+
*
95+
* using 'val' means once assigned a value reference, it cannot change (immutable)
96+
* using 'var' means it is a mutable reference
8797
*/
8898
fun someVariableStuff() {
8999
println("\n>>>>> Variables")
100+
90101
val implicitInt = 32 //type is implicit Int, val means the reference can only be set once
91102
// implicitInt = 33 //compile time fail uncomment to show
92103
// implicitInt = "string" //compile time reassign val error AND type mismatch error
93-
var varInt = implicitInt //valid, var can have it's reference changed
104+
var varInt = implicitInt //var has mutable reference, but once assigned a type it can't change
94105
println(" varInt = $varInt")
106+
// varInt = "blah" //type mismatch, once a var has a type assigned it can't change
107+
varInt = implicitInt * 2 //var has mutable reference
108+
println(" after changing reference varInt = $varInt")
95109
println(" varInt with ++ = ${++varInt}") //need {} to get ++ to work, ie an expression
96110
println(" varInt after increment = $varInt")
97111
}
@@ -118,13 +132,24 @@ fun simpleWhenAsExpression(a: Int) =
118132
else -> " range: a is out of range $a"
119133
}
120134

121-
//implicitly returns Unit
135+
/**
136+
* implicitly returns Unit
137+
* no need for casting after figuring type, ie no if(instanceof String) {String x - (String)obj
138+
*/
122139
fun whenWithSmartCast(a: Any) =
123140
when(a) {
124141
is String -> println(" smartcast: got a string: $a") //in block we don't have to do typcast, its automagic
125142
else -> println(" smartcast: not a string $a")
126143
}
127144

145+
fun someFunWithEquals() {
146+
println(" Showing equals")
147+
val personOne = Person("blah", "Johnny", "Walker")
148+
val personTwo = Person("blah", "Johnny", "Walker")
149+
println(" using == in place of .equals structural equality: ${personOne == personTwo}")
150+
println(" using === in place of .equals refernentioal equality: ${personOne === personTwo}")
151+
}
152+
128153
//implicitly returns Unit
129154
fun conditionals() {
130155
println("\n>>>> Conditionals")
@@ -137,6 +162,7 @@ fun conditionals() {
137162
println(" simple when as an expression out of range ${simpleWhenAsExpression(44)}")
138163
whenWithSmartCast(" smartCast with string 1")
139164
whenWithSmartCast(1)
165+
someFunWithEquals()
140166
}
141167

142168
/**
@@ -153,10 +179,33 @@ fun progression() {
153179
for(counter in 1..10 step 2) println(" progression of 2: $counter")
154180
}
155181

182+
/**
183+
* >>>>> Ranges
184+
*/
185+
fun doingStuffWithRanges() {
186+
println("\n>>>> stuff with ranges")
187+
print(" typical for loop\n ")
188+
for (i in 1..20) { print("$i,") }
189+
190+
print("\n using until for loop\n ")
191+
for (i in 0 until 20) { print("$i,") }
192+
193+
print("\n\n using a progression of 2 for loop\n ")
194+
for (i in 2..10 step 2) { print("$i,") }//progression of 2
195+
196+
print("\n\n Counting downward\n ")
197+
for (i in 10 downTo 1) { print("$i,") }
198+
199+
print("\n\n using range in a if statement\n ")
200+
val somenum = 8
201+
if (somenum in 1..10) { println("$somenum is in the range") }
202+
}
203+
156204
fun loops() {
157205
println("\n>>>> Loops")
158206
simpleForLoopOverRange()
159207
progression()
208+
doingStuffWithRanges()
160209
}
161210

162211
/**

src/main/kotlin/me/kotlindemo/02_Collections.kt

+42-7
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,57 @@
11
package me.kotlindemo
22

3+
import me.kotlindemo.classes.Beer
4+
35
fun main() {
46
iterateCollection()
57
lambdaFilterAndSearch()
6-
addABeer()
8+
collectionMutability()
79
someMapStuff()
10+
usingAnInitiailzerFunction()
811
}
912

1013
//note that these are var, but the underlying collections are immutable (see below)
11-
var taprooms = setOf("Roets", "Badger Hill", "Lucid", "Modist", "Lupin") //type is inferred to be string
12-
var beers = listOf("Dreamyard", "Bearded Lad", "Freethought", "Traitor IPA")
14+
var setOfTaprooms = setOf("Roets", "Badger Hill", "Lucid", "Modist", "Lupin") //type is inferred to be string
15+
var listOfBeers = listOf("Dreamyard", "Bearded Lad", "Freethought", "Traitor IPA")
1316
val mutableNumbers = mutableListOf("one", "two", "three") //list is mutable, but the REFERENCE is not, ie can't do the following
1417
//mutableNumbers = mutableListOf() //this fails compile error. Uncommnet to show
18+
val beers = listOf(
19+
Beer("Roets", "Roets IPA", 6.1, 62, "IPA"),
20+
Beer("Roets", "Berry", 5.8, 21, "Sour"),
21+
Beer("Badger Hill", "Traitor IPA", 5.5, 71, "IPA"),
22+
Beer("Castle Danger", "Castle Cream Ale", 5.5, 0, "Cream Ale"),
23+
Beer("Boathouse Brothers","Candy Cove",5.3, 12 , "Kolsch"),
24+
Beer("Wild Mind Ales", "Skateboard Guitar", 6.3, 10, "Sour"))
1525

1626
//key to value
1727
val mapOfNumbers = mapOf(1 to "one", 2 to "two", 3 to "three")
1828

1929
fun iterateCollection() {
2030
println("\n>>>> Iterate Collection")
21-
for (tapRoom in taprooms) { //for is not an expression can't do iterateCollection() = ...
31+
for (tapRoom in setOfTaprooms) { //for is not an expression can't do iterateCollection() = ...
2232
println("taproom: $tapRoom")
2333
}
2434

25-
for (beer in beers) {
35+
for (beer in listOfBeers) {
2636
println("beer: $beer")
2737
}
2838
}
2939

3040
fun lambdaFilterAndSearch() {
3141
println("\n>>>> lambdaSliceAndDice")
32-
taprooms.filter { it.startsWith("l", ignoreCase = true) }
42+
setOfTaprooms.filter { it.startsWith("l", ignoreCase = true) } //note no () for method call if lambda is last/only arg
3343
.sortedBy { it }
3444
.map { it.toUpperCase() }
3545
.forEach{println(it)}
46+
47+
println(" now do same on a list of objects")
48+
beers.filter { it.ibu > 10 }
49+
.sortedBy { it.abv }
50+
.map { it.brewer + ": " + it.name }
51+
.forEach{println(it)}
3652
}
3753

38-
fun addABeer() {
54+
fun collectionMutability() {
3955
println("\n>>>> mutability of Collection")
4056

4157
// beers.add("beer") //invalid compile check, immutable list, ie add does not exist
@@ -54,3 +70,22 @@ fun someMapStuff() {
5470
}
5571
}
5672

73+
fun usingAnInitiailzerFunction() {
74+
println(" \nInit a list")
75+
val listOInts = List(30) {it + 1} //it is the index of the element
76+
println(" list populated via it + 1 initialzer $listOInts")
77+
78+
val listFromAnotherInitializer = List(30) {it}
79+
println(" list populated via a it initialzer $listFromAnotherInitializer")
80+
//note the 2 different initializers are the same
81+
82+
val listFromRange = (1..30).toList()
83+
println(" list populated by a range: $listFromRange")
84+
85+
//sequences are lazy by default, in this case the toList does cause it to not be lazy or mem efficiant
86+
val fromASequence = generateSequence(1) { it + 1 }.takeWhile { it <= 30 }.toList()
87+
println(" List populated via a sequence: $fromASequence")
88+
}
89+
90+
// val numbers: List<Int> = emptyList() //readonly empty list.
91+
// val mutableList = mutableListOf<Int>() //need a mutable list to add to it.

src/main/kotlin/me/kotlindemo/classes/Classes.kt

+2
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ package me.kotlindemo.classes
1515
*/
1616
data class Person(val id: String, var firstName: String, val lastName: String, val age: Int = 31) //note age has default value, makes it optional in constructor
1717

18+
data class Beer(val brewer: String, val name: String, val abv: Double, val ibu: Int, val style: String)
19+
1820
fun main() {
1921
showDataClass()
2022
}

0 commit comments

Comments
 (0)