Regenerated samples
This commit is contained in:
parent
a461accc4c
commit
9a5a6aa5cf
|
@ -2,8 +2,8 @@
|
|||
package interoperability;
|
||||
import java.io.Serializable;
|
||||
|
||||
public class Chameleon
|
||||
implements Serializable {
|
||||
public
|
||||
class Chameleon implements Serializable {
|
||||
private int size;
|
||||
private String color;
|
||||
public int getSize() {
|
||||
|
|
|
@ -5,21 +5,23 @@ import static atomictest.AtomicTestKt.eq;
|
|||
|
||||
public class UseDataClass {
|
||||
public static void main(String[] args) {
|
||||
Muppet m = new Muppet("Ernie", 6);
|
||||
int ageErnie = m.getAge();
|
||||
m.setName("Bert");
|
||||
m.setAge(7);
|
||||
eq(ageErnie < m.getAge(), true);
|
||||
eq(m, "Muppet(name=Bert, age=7)");
|
||||
Staff e = new Staff(
|
||||
"Fluffy", "Office Manager");
|
||||
eq(e.getRole(), "Office Manager");
|
||||
e.setName("Uranus");
|
||||
e.setRole("Assistant");
|
||||
eq(e,
|
||||
"Staff(name=Uranus, role=Assistant)");
|
||||
|
||||
// Call copy() from the data class:
|
||||
Muppet mc = m.copy("???", 5);
|
||||
eq(mc, "Muppet(name=???, age=5)");
|
||||
Staff cf = e.copy("Cornfed", "Sidekick");
|
||||
eq(cf,
|
||||
"Staff(name=Cornfed, role=Sidekick)");
|
||||
|
||||
HashMap<Muppet, String> hm =
|
||||
HashMap<Staff, String> hm =
|
||||
new HashMap<>();
|
||||
// Muppets work as hash keys:
|
||||
hm.put(m, "Happy Muppet");
|
||||
eq(hm.get(m), "Happy Muppet");
|
||||
// Employees work as hash keys:
|
||||
hm.put(e, "Cheerful");
|
||||
eq(hm.get(e), "Cheerful");
|
||||
}
|
||||
}
|
|
@ -1,7 +1,7 @@
|
|||
// interoperability/KotlinDataClass.kt
|
||||
package interoperability
|
||||
|
||||
data class Muppet(
|
||||
data class Staff(
|
||||
var name: String,
|
||||
var age: Int
|
||||
var role: String
|
||||
)
|
|
@ -1,9 +1,10 @@
|
|||
// HigherOrderFunctions/RepeatByInt.kt
|
||||
import atomictest.*
|
||||
|
||||
fun main() {
|
||||
repeat(2) { println("hi!") }
|
||||
}
|
||||
/* Output:
|
||||
hi!
|
||||
hi!
|
||||
*/
|
||||
repeat(2) { trace("hi!") }
|
||||
trace eq """
|
||||
hi!
|
||||
hi!
|
||||
"""
|
||||
}
|
|
@ -1,5 +1,6 @@
|
|||
// HigherOrderFunctions/RepeatFun.kt
|
||||
package definingrepeat
|
||||
import atomictest.*
|
||||
|
||||
fun repeat(
|
||||
times: Int,
|
||||
|
@ -11,10 +12,10 @@ fun repeat(
|
|||
}
|
||||
|
||||
fun main() {
|
||||
repeat(3) { println("#$it") } // [3]
|
||||
}
|
||||
/* Output:
|
||||
#0
|
||||
#1
|
||||
#2
|
||||
*/
|
||||
repeat(3) { trace("#$it") } // [3]
|
||||
trace eq """
|
||||
#0
|
||||
#1
|
||||
#2
|
||||
"""
|
||||
}
|
|
@ -1,9 +1,10 @@
|
|||
// HigherOrderFunctions/RepeatVerbose.kt
|
||||
import atomictest.*
|
||||
|
||||
fun main() {
|
||||
repeat(2, { println("hi!") })
|
||||
}
|
||||
/* Output:
|
||||
hi!
|
||||
hi!
|
||||
*/
|
||||
repeat(2, { trace("hi!") })
|
||||
trace eq """
|
||||
hi!
|
||||
hi!
|
||||
"""
|
||||
}
|
|
@ -1,11 +1,11 @@
|
|||
// Lambdas/ZeroArguments.kt
|
||||
import atomictest.eq
|
||||
import atomictest.*
|
||||
|
||||
fun main() {
|
||||
run { -> println("A Lambda") }
|
||||
run { println("Without args") }
|
||||
}
|
||||
/* Output:
|
||||
A Lambda
|
||||
Without args
|
||||
*/
|
||||
run { -> trace("A Lambda") }
|
||||
run { trace("Without args") }
|
||||
trace eq """
|
||||
A Lambda
|
||||
Without args
|
||||
"""
|
||||
}
|
|
@ -1,13 +1,13 @@
|
|||
// LocalFunctions/CustomLabel.kt
|
||||
import atomictest.eq
|
||||
|
||||
fun main() {
|
||||
val list = listOf(1, 2, 3, 4, 5)
|
||||
val value = 3
|
||||
var result = ""
|
||||
list.forEach tag@{ // [1]
|
||||
result += "$it"
|
||||
if (it == value) return@tag // [2]
|
||||
}
|
||||
println("This line is called")
|
||||
}
|
||||
/* Output:
|
||||
This line is called
|
||||
*/
|
||||
result eq "12345"
|
||||
}
|
|
@ -1,13 +1,13 @@
|
|||
// LocalFunctions/LabeledReturn.kt
|
||||
import atomictest.eq
|
||||
|
||||
fun main() {
|
||||
val list = listOf(1, 2, 3, 4, 5)
|
||||
val value = 3
|
||||
var result = ""
|
||||
list.forEach {
|
||||
result += "$it"
|
||||
if (it == value) return@forEach
|
||||
}
|
||||
println("This line is called")
|
||||
}
|
||||
/* Output:
|
||||
This line is called
|
||||
*/
|
||||
result eq "12345"
|
||||
}
|
|
@ -1,4 +1,5 @@
|
|||
// LocalFunctions/LocalFunctions.kt
|
||||
import atomictest.eq
|
||||
|
||||
fun main() {
|
||||
val logMsg = StringBuilder()
|
||||
|
@ -7,9 +8,8 @@ fun main() {
|
|||
log("Starting computation")
|
||||
val x = 42 // Imitate computation
|
||||
log("Computation result: $x")
|
||||
println(logMsg.toString())
|
||||
}
|
||||
/* Output:
|
||||
Starting computation
|
||||
Computation result: 42
|
||||
*/
|
||||
logMsg.toString().trim() eq """
|
||||
Starting computation
|
||||
Computation result: 42
|
||||
"""
|
||||
}
|
|
@ -1,12 +1,16 @@
|
|||
// LocalFunctions/ReturnFromFun.kt
|
||||
import atomictest.eq
|
||||
|
||||
fun main() {
|
||||
val list = listOf(1, 2, 3, 4, 5)
|
||||
val value = 3
|
||||
var result = ""
|
||||
list.forEach {
|
||||
if (it == value) return // [1]
|
||||
result += "$it"
|
||||
if (it == value) {
|
||||
result eq "123"
|
||||
return // [1]
|
||||
}
|
||||
}
|
||||
println("This line is NOT called") // [2]
|
||||
}
|
||||
/* Output:
|
||||
*/
|
||||
result eq "Never gets here" // [2]
|
||||
}
|
|
@ -12,13 +12,14 @@ fun main() {
|
|||
Product("bread", 2.0),
|
||||
Product("wine", 5.0)
|
||||
)
|
||||
val cheapest = products.minByOrNull { it.price }
|
||||
cheapest eq Product("bread", 2.0)
|
||||
|
||||
val sum = products.sumByDouble { it.price }
|
||||
sum eq 7.0
|
||||
|
||||
products.sortedByDescending { it.price } eq
|
||||
"[Product(description=wine, price=5.0)," +
|
||||
" Product(description=bread, price=2.0)]"
|
||||
|
||||
val cheapest =
|
||||
products.minByOrNull { it.price }
|
||||
cheapest eq Product("bread", 2.0)
|
||||
}
|
|
@ -3,7 +3,7 @@ import atomictest.eq
|
|||
|
||||
fun main() {
|
||||
val set = setOf("a", "ab", "ac")
|
||||
set.maxBy { it.length }?.length eq 2
|
||||
set.maxByOrNull { it.length }?.length eq 2
|
||||
set.filter {
|
||||
it.contains('b')
|
||||
} eq listOf("ab")
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
## Lists (#1)
|
||||
|
||||
The Kotlin standard library contains many functions that work with `Lists`.
|
||||
The Kotlin standard library contains many functions that work with `List`s.
|
||||
It's educational to implement some of them by hand.
|
||||
|
||||
Write a function `findMax()` that finds the maximum value in a `List` of
|
||||
|
|
|
@ -6,8 +6,8 @@ original letters exactly once.
|
|||
|
||||
<div class="hint">
|
||||
|
||||
Compare two sorted `Lists` of characters obtained from two `String`s.
|
||||
Convert a `String` to a `List` by calling `toList()`. If the `Lists` are equal,
|
||||
Compare two sorted `List`s of characters obtained from two `String`s.
|
||||
Convert a `String` to a `List` by calling `toList()`. If the `List`s are equal,
|
||||
the words are anagrams. For example, for two anagrams "terrain" and "trainer"
|
||||
the sorted character `List` will be `[a, e, i, n, r, r, t]`.
|
||||
|
||||
|
|
|
@ -4,10 +4,10 @@ import atomictest.eq
|
|||
|
||||
class Contact(
|
||||
val name: String,
|
||||
val number: String
|
||||
val phone: String
|
||||
) {
|
||||
override fun toString(): String {
|
||||
return "Contact('$name', '$number')"
|
||||
return "Contact('$name', '$phone')"
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -15,8 +15,8 @@ fun main() {
|
|||
val miffy = Contact("Miffy", "1-234-567890")
|
||||
val cleo = Contact("Cleo", "098-765-4321")
|
||||
val contacts = mapOf(
|
||||
miffy.number to miffy,
|
||||
cleo.number to cleo)
|
||||
miffy.phone to miffy,
|
||||
cleo.phone to cleo)
|
||||
contacts["1-234-567890"] eq miffy
|
||||
contacts["1-111-111111"] eq null
|
||||
}
|
|
@ -8,4 +8,6 @@ fun main() {
|
|||
map.getValue('b')
|
||||
} eq "NoSuchElementException: " +
|
||||
"Key b is missing in the map."
|
||||
map.getOrDefault('a', "??") eq "attempt"
|
||||
map.getOrDefault('b', "??") eq "??"
|
||||
}
|
|
@ -5,7 +5,8 @@ fun main() {
|
|||
val constants = mapOf(
|
||||
"Pi" to 3.141,
|
||||
"e" to 2.718,
|
||||
"phi" to 1.618)
|
||||
"phi" to 1.618
|
||||
)
|
||||
constants eq
|
||||
"{Pi=3.141, e=2.718, phi=1.618}"
|
||||
|
||||
|
|
|
@ -1,14 +1,15 @@
|
|||
// PropertyAccessors/Default.kt
|
||||
package propertyaccessors
|
||||
import atomictest.*
|
||||
|
||||
class Default {
|
||||
var i: Int = 0
|
||||
get() {
|
||||
println("get()")
|
||||
trace("get()")
|
||||
return field // [1]
|
||||
}
|
||||
set(value) {
|
||||
println("set($value)")
|
||||
trace("set($value)")
|
||||
field = value // [2]
|
||||
}
|
||||
}
|
||||
|
@ -16,10 +17,10 @@ class Default {
|
|||
fun main() {
|
||||
val d = Default()
|
||||
d.i = 2
|
||||
println(d.i)
|
||||
}
|
||||
/* Output:
|
||||
set(2)
|
||||
get()
|
||||
2
|
||||
*/
|
||||
trace(d.i)
|
||||
trace eq """
|
||||
set(2)
|
||||
get()
|
||||
2
|
||||
"""
|
||||
}
|
|
@ -1,11 +1,11 @@
|
|||
// PropertyAccessors/LogChanges.kt
|
||||
package propertyaccessors
|
||||
import atomictest.eq
|
||||
import atomictest.*
|
||||
|
||||
class LogChanges {
|
||||
var n: Int = 0
|
||||
set(value) {
|
||||
println("$field becomes $value")
|
||||
trace("$field becomes $value")
|
||||
field = value
|
||||
}
|
||||
}
|
||||
|
@ -15,9 +15,5 @@ fun main() {
|
|||
lc.n eq 0
|
||||
lc.n = 2
|
||||
lc.n eq 2
|
||||
}
|
||||
/* Output:
|
||||
0
|
||||
0 becomes 2
|
||||
2
|
||||
*/
|
||||
trace eq "0 becomes 2"
|
||||
}
|
|
@ -5,6 +5,5 @@ fun main() {
|
|||
val list = listOf(3, 3, 2, 1, 2)
|
||||
list.toSet() eq setOf(1, 2, 3)
|
||||
list.distinct() eq listOf(3, 2, 1)
|
||||
|
||||
"abbcc".toSet() eq setOf('a', 'b', 'c')
|
||||
}
|
|
@ -16,13 +16,15 @@ fun main() {
|
|||
ascii.keys eq "[A, B, C, I, J, K]"
|
||||
ascii.values eq
|
||||
"[65, 66, 67, 73, 74, 75]"
|
||||
var kv = ""
|
||||
for (entry in ascii) { // [2]
|
||||
print("${entry.key}:${entry.value},")
|
||||
kv += "${entry.key}:${entry.value},"
|
||||
}
|
||||
println()
|
||||
kv eq "A:65,B:66,C:67,I:73,J:74,K:75,"
|
||||
kv = ""
|
||||
for ((key, value) in ascii) // [3]
|
||||
print("$key:$value,")
|
||||
println()
|
||||
kv += "$key:$value,"
|
||||
kv eq "A:65,B:66,C:67,I:73,J:74,K:75,"
|
||||
val mutable = ascii.toMutableMap() // [4]
|
||||
mutable.remove("I")
|
||||
mutable eq
|
||||
|
@ -33,15 +35,4 @@ fun main() {
|
|||
mutable.clear()
|
||||
mutable["A"] = 100
|
||||
mutable eq "{A=100}"
|
||||
}
|
||||
/* Output:
|
||||
{A=65, B=66, C=67, I=73, J=74, K=75}
|
||||
66
|
||||
[A, B, C, I, J, K]
|
||||
[65, 66, 67, 73, 74, 75]
|
||||
A:65,B:66,C:67,I:73,J:74,K:75,
|
||||
A:65,B:66,C:67,I:73,J:74,K:75,
|
||||
{A=65, B=66, C=67, J=74, K=75}
|
||||
{A=65, B=66, C=67, J=74, K=75, Z=90}
|
||||
{A=100}
|
||||
*/
|
||||
}
|
|
@ -1,5 +1,6 @@
|
|||
// Summary2/ArraySpread.kt
|
||||
import summary2.varargs
|
||||
import atomictest.trace
|
||||
|
||||
fun main() {
|
||||
val array = intArrayOf(4, 5) // [1]
|
||||
|
@ -7,8 +8,19 @@ fun main() {
|
|||
val list = listOf(9, 10, 11)
|
||||
varargs(
|
||||
"y", 7, 8, *list.toIntArray()) // [3]
|
||||
}
|
||||
/* Output:
|
||||
1 2 3 4 5 6 x
|
||||
7 8 9 10 11 y
|
||||
*/
|
||||
trace eq """
|
||||
1
|
||||
2
|
||||
3
|
||||
4
|
||||
5
|
||||
6
|
||||
x
|
||||
7
|
||||
8
|
||||
9
|
||||
10
|
||||
11
|
||||
y
|
||||
"""
|
||||
}
|
|
@ -1,5 +1,6 @@
|
|||
// Summary2/Boxes.kt
|
||||
package summary2
|
||||
import atomictest.*
|
||||
|
||||
private var count = 0 // [1]
|
||||
|
||||
|
@ -11,7 +12,7 @@ private class Box(val dimension: Int) { // [2]
|
|||
}
|
||||
|
||||
private fun countBox(box: Box) { // [3]
|
||||
println("$box")
|
||||
trace("$box")
|
||||
count++
|
||||
}
|
||||
|
||||
|
@ -22,10 +23,10 @@ fun countBoxes() {
|
|||
|
||||
fun main() {
|
||||
countBoxes()
|
||||
println("$count boxes")
|
||||
}
|
||||
/* Output:
|
||||
Box volume: 64
|
||||
Box volume: 125
|
||||
2 boxes
|
||||
*/
|
||||
trace("$count boxes")
|
||||
trace eq """
|
||||
Box volume: 64
|
||||
Box volume: 125
|
||||
2 boxes
|
||||
"""
|
||||
}
|
|
@ -1,14 +1,15 @@
|
|||
// Summary2/GetterAndSetter.kt
|
||||
package summary2
|
||||
import atomictest.*
|
||||
|
||||
class GetterAndSetter {
|
||||
var i: Int = 0
|
||||
get() {
|
||||
println("get()")
|
||||
trace("get()")
|
||||
return field
|
||||
}
|
||||
set(value) {
|
||||
println("set($value)")
|
||||
trace("set($value)")
|
||||
field = value
|
||||
}
|
||||
}
|
||||
|
@ -16,10 +17,10 @@ class GetterAndSetter {
|
|||
fun main() {
|
||||
val gs = GetterAndSetter()
|
||||
gs.i = 2
|
||||
println(gs.i)
|
||||
}
|
||||
/* Output:
|
||||
set(2)
|
||||
get()
|
||||
2
|
||||
*/
|
||||
trace(gs.i)
|
||||
trace eq """
|
||||
set(2)
|
||||
get()
|
||||
2
|
||||
"""
|
||||
}
|
|
@ -1,5 +1,6 @@
|
|||
// Summary2/JetPack.kt
|
||||
package summary2
|
||||
import atomictest.eq
|
||||
|
||||
class JetPack(
|
||||
private var fuel: Double // [1]
|
||||
|
@ -22,14 +23,8 @@ class JetPack(
|
|||
fun main() {
|
||||
val jetPack = JetPack(3.0)
|
||||
while (jetPack.check() != "Warning") {
|
||||
println(jetPack.check())
|
||||
jetPack.check() eq "OK"
|
||||
jetPack.fly()
|
||||
}
|
||||
println(jetPack.check())
|
||||
}
|
||||
/* Output:
|
||||
OK
|
||||
OK
|
||||
OK
|
||||
Warning
|
||||
*/
|
||||
jetPack.check() eq "Warning"
|
||||
}
|
|
@ -1,23 +1,23 @@
|
|||
// Summary2/ListOfStrings.kt
|
||||
import atomictest.*
|
||||
|
||||
fun main() {
|
||||
val jabber = """
|
||||
val wocky = """
|
||||
Twas brillig, and the slithy toves
|
||||
Did gyre and gimble in the wabe:
|
||||
All mimsy were the borogoves,
|
||||
And the mome raths outgrabe.
|
||||
""".trim().split(Regex("\\W+"))
|
||||
println(jabber.take(5))
|
||||
println(jabber.slice(6..12))
|
||||
println(jabber.slice(6..18 step 2))
|
||||
println(jabber.sorted().takeLast(5))
|
||||
println(
|
||||
jabber.sorted().distinct().takeLast(5))
|
||||
}
|
||||
/* Output:
|
||||
[Twas, brillig, and, the, slithy]
|
||||
[Did, gyre, and, gimble, in, the, wabe]
|
||||
[Did, and, in, wabe, mimsy, the, And]
|
||||
[the, the, toves, wabe, were]
|
||||
[slithy, the, toves, wabe, were]
|
||||
*/
|
||||
trace(wocky.take(5))
|
||||
trace(wocky.slice(6..12))
|
||||
trace(wocky.slice(6..18 step 2))
|
||||
trace(wocky.sorted().takeLast(5))
|
||||
trace(wocky.sorted().distinct().takeLast(5))
|
||||
trace eq """
|
||||
[Twas, brillig, and, the, slithy]
|
||||
[Did, gyre, and, gimble, in, the, wabe]
|
||||
[Did, and, in, wabe, mimsy, the, And]
|
||||
[the, the, toves, wabe, were]
|
||||
[slithy, the, toves, wabe, were]
|
||||
"""
|
||||
}
|
|
@ -1,20 +1,20 @@
|
|||
// Summary2/ReadonlyVsMutableList.kt
|
||||
import atomictest.eq
|
||||
import atomictest.*
|
||||
|
||||
fun main() {
|
||||
val ints = listOf(5, 13, 9)
|
||||
// ints.add(11) // 'add()' not available
|
||||
for (i in ints) {
|
||||
if (i > 10) {
|
||||
println(i)
|
||||
trace(i)
|
||||
}
|
||||
}
|
||||
val chars = mutableListOf('a', 'b', 'c')
|
||||
chars.add('d') // 'add()' available
|
||||
chars += 'e'
|
||||
println(chars)
|
||||
}
|
||||
/* Output:
|
||||
13
|
||||
[a, b, c, d, e]
|
||||
*/
|
||||
trace(chars)
|
||||
trace eq """
|
||||
13
|
||||
[a, b, c, d, e]
|
||||
"""
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
// Testing/UsingTrace.kt
|
||||
import atomictest.*
|
||||
|
||||
fun main() {
|
||||
trace("Hello,")
|
||||
trace(47)
|
||||
trace("World!")
|
||||
trace eq """
|
||||
Hello,
|
||||
47
|
||||
World!
|
||||
"""
|
||||
}
|
|
@ -1,16 +1,24 @@
|
|||
// Summary2/VarArgs.kt
|
||||
package summary2
|
||||
import atomictest.*
|
||||
|
||||
fun varargs(s: String, vararg ints: Int) {
|
||||
for (i in ints) {
|
||||
print("$i ")
|
||||
trace("$i")
|
||||
}
|
||||
println(s)
|
||||
trace(s)
|
||||
}
|
||||
|
||||
fun main() {
|
||||
varargs("primes", 5, 7, 11, 13, 17, 19, 23)
|
||||
}
|
||||
/* Output:
|
||||
5 7 11 13 17 19 23 primes
|
||||
*/
|
||||
trace eq """
|
||||
5
|
||||
7
|
||||
11
|
||||
13
|
||||
17
|
||||
19
|
||||
23
|
||||
primes
|
||||
"""
|
||||
}
|
|
@ -6,6 +6,8 @@ files:
|
|||
visible: true
|
||||
- name: src/UsingAtomicTest.kt
|
||||
visible: true
|
||||
- name: src/UsingTrace.kt
|
||||
visible: true
|
||||
- name: src/ListCollection.kt
|
||||
visible: true
|
||||
- name: src/ClassBodies.kt
|
||||
|
|
|
@ -12,6 +12,8 @@ fun main() {
|
|||
// 'neq' means "not equal"
|
||||
v2 neq "Epistimology"
|
||||
|
||||
// [Error] Epistimology != Ontology
|
||||
// v2 eq "Epistimology"
|
||||
}
|
||||
/* Output:
|
||||
11
|
||||
|
|
|
@ -1,18 +1,18 @@
|
|||
// Varargs/TwoFunctionsWithVarargs.kt
|
||||
package varargs
|
||||
import atomictest.eq
|
||||
|
||||
fun first(vararg numbers: Int) {
|
||||
fun first(vararg numbers: Int): String {
|
||||
var result = ""
|
||||
for (i in numbers) {
|
||||
print("[$i]")
|
||||
result += "[$i]"
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
fun second(vararg numbers: Int) =
|
||||
first(*numbers)
|
||||
|
||||
fun main() {
|
||||
second(7, 9, 32)
|
||||
}
|
||||
/* Output:
|
||||
[7][9][32]
|
||||
*/
|
||||
second(7, 9, 32) eq "[7][9][32]"
|
||||
}
|
|
@ -1,17 +1,16 @@
|
|||
// Varargs/VarargLikeList.kt
|
||||
package varargs
|
||||
import atomictest.eq
|
||||
|
||||
fun evaluate(vararg ints: Int) {
|
||||
println("Size: ${ints.size}")
|
||||
println("Sum: ${ints.sum()}")
|
||||
println("Average: ${ints.average()}")
|
||||
}
|
||||
fun evaluate(vararg ints: Int) =
|
||||
"Size: ${ints.size}\n" +
|
||||
"Sum: ${ints.sum()}\n" +
|
||||
"Average: ${ints.average()}"
|
||||
|
||||
fun main() {
|
||||
evaluate(10, -3, 8, 1, 9)
|
||||
}
|
||||
/* Output:
|
||||
Size: 5
|
||||
Sum: 25
|
||||
Average: 5.0
|
||||
*/
|
||||
evaluate(10, -3, 8, 1, 9) eq """
|
||||
Size: 5
|
||||
Sum: 25
|
||||
Average: 5.0
|
||||
"""
|
||||
}
|
|
@ -4,4 +4,4 @@ The starter code contains an `open` class `Cleanser` and a class `Detergent`
|
|||
that inherits it. Add to the `Cleanser` class the property
|
||||
`var ops: MutableList<String>` and the functions `dilute()`, `apply()` and
|
||||
`scrub()` that simply add their names to `ops`. In `main`, make sure that
|
||||
`Detergent` has now the same functions as `Cleanser`.
|
||||
`Detergent` now has the same functions as `Cleanser`.
|
||||
|
|
|
@ -3,11 +3,11 @@ package innerclasses
|
|||
import atomictest.eq
|
||||
import typechecking.name
|
||||
|
||||
class Fruit { // implicit label @Fruit
|
||||
class Fruit { // Implicit label @Fruit
|
||||
fun changeColor(color: String) =
|
||||
"Fruit $color"
|
||||
fun absorbWater(amount: Int) {}
|
||||
inner class Seed { // implicit label @Seed
|
||||
inner class Seed { // Implicit label @Seed
|
||||
fun changeColor(color: String) =
|
||||
"Seed $color"
|
||||
fun germinate() {}
|
||||
|
@ -22,7 +22,7 @@ class Fruit { // implicit label @Fruit
|
|||
// Cannot access a further-inner class:
|
||||
// this@DNA.name
|
||||
}
|
||||
inner class DNA { // implicit label @DNA
|
||||
inner class DNA { // Implicit label @DNA
|
||||
fun changeColor(color: String) {
|
||||
// changeColor(color) // Recursive
|
||||
this@Seed.changeColor(color)
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
## Interfaces (#3)
|
||||
|
||||
Now define a property `sound` of the `String` type inside the `Pet` interface
|
||||
and implement it inside classes to return `dog`, `cat`, and `hamster`
|
||||
appropriately. In `main()`, as in the previous task, create a `List<Pet>`
|
||||
containing all three types of `Pet` and iterate through the `List` and print the
|
||||
value of `sound` for each `Pet`.
|
||||
Define a property `sound` of type `String` inside the `Pet` interface and
|
||||
implement it inside classes to return "Bark!" for `Dog`, "Meow!" for `Cat`, and
|
||||
"Squeak!" for `Hamster`. In `main()`, as in the previous task, create a
|
||||
`List<Pet>` containing all three types of `Pet`. Iterate through the `List` and
|
||||
print the value of `sound` for each `Pet`.
|
||||
|
|
|
@ -1,42 +1,41 @@
|
|||
// SecondaryConstructors/WithSecondary.kt
|
||||
package secondaryconstructors
|
||||
import atomictest.*
|
||||
|
||||
class WithSecondary(i: Int) {
|
||||
init {
|
||||
println("Primary: $i")
|
||||
trace("Primary: $i")
|
||||
}
|
||||
|
||||
constructor(c: Char) : this(c - 'A') {
|
||||
println("Secondary: '$c'")
|
||||
trace("Secondary: '$c'")
|
||||
}
|
||||
|
||||
constructor(s: String) :
|
||||
this(s.first()) { // [1]
|
||||
println("Secondary: \"$s\"")
|
||||
trace("Secondary: \"$s\"")
|
||||
}
|
||||
/* Doesn't compile without a call
|
||||
to the primary constructor:
|
||||
constructor(f: Float) { // [2]
|
||||
println("Secondary: $f")
|
||||
trace("Secondary: $f")
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
fun main() {
|
||||
fun sep() = println("-".repeat(10))
|
||||
fun sep() = trace("-".repeat(10))
|
||||
WithSecondary(1)
|
||||
sep()
|
||||
WithSecondary('D')
|
||||
sep()
|
||||
WithSecondary("Last Constructor")
|
||||
}
|
||||
/* Output:
|
||||
Primary: 1
|
||||
----------
|
||||
Primary: 3
|
||||
Secondary: 'D'
|
||||
----------
|
||||
Primary: 11
|
||||
Secondary: 'L'
|
||||
Secondary: "Last Constructor"
|
||||
*/
|
||||
trace eq """
|
||||
Primary: 1
|
||||
----------
|
||||
Primary: 3
|
||||
Secondary: 'D'
|
||||
----------
|
||||
Primary: 11
|
||||
Secondary: 'L'
|
||||
Secondary: "Last Constructor"
|
||||
"""
|
||||
}
|
|
@ -3,12 +3,12 @@ package extensionlambdas
|
|||
import atomictest.eq
|
||||
|
||||
fun exec(
|
||||
arg1: Int, arg2: Int,
|
||||
f: Int.(Int) -> Boolean
|
||||
arg1: Int, arg2: Int,
|
||||
f: Int.(Int) -> Boolean
|
||||
) = arg1.f(arg2)
|
||||
|
||||
fun main() {
|
||||
exec(10, 2, fun Int.(d: Int): Boolean {
|
||||
return this % d == 0
|
||||
}) eq true
|
||||
exec(10, 2, fun Int.(d: Int): Boolean {
|
||||
return this % d == 0
|
||||
}) eq true
|
||||
}
|
|
@ -14,13 +14,8 @@ val charmap: Map<Char, Int> = buildMap {
|
|||
}
|
||||
}
|
||||
|
||||
val charmapNoBuilder: Map<Char, Int> =
|
||||
('A'..'F').foldIndexed(emptyMap()) {
|
||||
idx, acc, char -> acc.plus(char to idx)
|
||||
}
|
||||
|
||||
fun main() {
|
||||
characters eq "[Chars:, a, b, c, d]"
|
||||
// characters eq characters2
|
||||
charmap eq "{A=0, B=1, C=2, D=3, E=4, F=5}"
|
||||
charmap eq charmapNoBuilder
|
||||
}
|
|
@ -5,12 +5,12 @@ import atomictest.eq
|
|||
|
||||
fun main() {
|
||||
val func: (String) -> Int = { it.length }
|
||||
val nullableFunc: ((String) -> Int)? = null
|
||||
func("abc") eq 3
|
||||
func.invoke("abc") eq 3
|
||||
|
||||
val nullableFunc: ((String) -> Int)? = null
|
||||
if (nullableFunc != null) {
|
||||
nullableFunc("abc")
|
||||
}
|
||||
nullableFunc?.invoke("abc")
|
||||
nullableFunc?.invoke("abc") // [1]
|
||||
}
|
|
@ -28,9 +28,9 @@ files:
|
|||
visible: true
|
||||
- name: src/StringInvoke.kt
|
||||
visible: true
|
||||
- name: src/InvokeFunctionType.kt
|
||||
visible: true
|
||||
- name: src/Backticks.kt
|
||||
visible: true
|
||||
- name: src/Swearing.kt
|
||||
visible: true
|
||||
- name: src/InvokeFunctionType.kt
|
||||
visible: true
|
||||
|
|
|
@ -0,0 +1,57 @@
|
|||
// ScopeFunctions/Differences.kt
|
||||
package scopefunctions
|
||||
import atomictest.eq
|
||||
|
||||
data class Tag(var n: Int = 0) {
|
||||
var s: String = ""
|
||||
fun increment() = ++n
|
||||
}
|
||||
|
||||
fun main() {
|
||||
// let(): Access object with 'it'
|
||||
// Returns last expression in lambda
|
||||
Tag(1).let {
|
||||
it.s = "let: ${it.n}"
|
||||
it.increment()
|
||||
} eq 2
|
||||
|
||||
// let() with named lambda argument:
|
||||
Tag(2).let { tag ->
|
||||
tag.s = "let: ${tag.n}"
|
||||
tag.increment()
|
||||
} eq 3
|
||||
|
||||
// run(): Access object with 'this'
|
||||
// Returns last expression in lambda
|
||||
Tag(3).run {
|
||||
s = "run: $n" // Implicit 'this'
|
||||
increment() // Implicit 'this'
|
||||
} eq 4
|
||||
|
||||
// with(): Access object with 'this'
|
||||
// Returns last expression in lambda
|
||||
with(Tag(4)) {
|
||||
s = "with: $n"
|
||||
increment()
|
||||
} eq 5
|
||||
|
||||
// apply(): Access object with 'this'
|
||||
// Returns modified object
|
||||
Tag(5).apply {
|
||||
s = "apply: $n"
|
||||
increment()
|
||||
} eq "Tag(n=6)"
|
||||
|
||||
// also(): Access object with 'it'
|
||||
// Returns modified object
|
||||
Tag(6).also {
|
||||
it.s = "also: ${it.n}"
|
||||
it.increment()
|
||||
} eq "Tag(n=7)"
|
||||
|
||||
// also() with named lambda argument:
|
||||
Tag(7).also { tag ->
|
||||
tag.s = "also: ${tag.n}"
|
||||
tag.increment()
|
||||
} eq "Tag(n=8)"
|
||||
}
|
|
@ -1,5 +1,7 @@
|
|||
type: theory
|
||||
files:
|
||||
- name: src/Differences.kt
|
||||
visible: true
|
||||
- name: src/AndNullability.kt
|
||||
visible: true
|
||||
- name: src/Gnome.kt
|
||||
|
|
|
@ -19,12 +19,12 @@ fun main() {
|
|||
} catch (e: IncorrectInputException) {
|
||||
e.message eq "Code must be > 1000: 161"
|
||||
} catch (e: IllegalArgumentException) {
|
||||
println("Shouldn't get here")
|
||||
"Produces error" eq "if it gets here"
|
||||
}
|
||||
try {
|
||||
checkCode("1".toInt(1))
|
||||
} catch (e: IncorrectInputException) {
|
||||
println("Shouldn't get here")
|
||||
"Produces error" eq "if it gets here"
|
||||
} catch (e: IllegalArgumentException) {
|
||||
e.message eq
|
||||
"radix 1 was not in valid range 2..36"
|
||||
|
|
|
@ -12,4 +12,4 @@ Display half of a triangle. For an argument of 6 the function
|
|||
######
|
||||
```
|
||||
|
||||
Now rewrite the function to use `repeat` instead of a `for` loop.
|
||||
Now rewrite the function to use `repeat`.
|
||||
|
|
|
@ -1,14 +1,13 @@
|
|||
// Enumerations/CheckingOptions.kt
|
||||
package enumerations
|
||||
import atomictest.eq
|
||||
import enumerations.Level
|
||||
import atomictest.*
|
||||
import enumerations.Level.*
|
||||
|
||||
fun checkLevel(level: Level) {
|
||||
when (level) {
|
||||
Overflow -> println(">>> Overflow!")
|
||||
Empty -> println("Alert: Empty")
|
||||
else -> println("Level $level OK")
|
||||
Overflow -> trace(">>> Overflow!")
|
||||
Empty -> trace("Alert: Empty")
|
||||
else -> trace("Level $level OK")
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -16,9 +15,9 @@ fun main() {
|
|||
checkLevel(Empty)
|
||||
checkLevel(Low)
|
||||
checkLevel(Overflow)
|
||||
}
|
||||
/* Output:
|
||||
Alert: Empty
|
||||
Level Low OK
|
||||
>>> Overflow!
|
||||
*/
|
||||
trace eq """
|
||||
Alert: Empty
|
||||
Level Low OK
|
||||
>>> Overflow!
|
||||
"""
|
||||
}
|
|
@ -5,7 +5,7 @@ import atomictest.eq
|
|||
fun color(
|
||||
red: Int = 0,
|
||||
green: Int = 0,
|
||||
blue: Int = 0
|
||||
blue: Int = 0,
|
||||
) = "($red, $green, $blue)"
|
||||
|
||||
fun main() {
|
||||
|
|
|
@ -5,7 +5,7 @@ import atomictest.eq
|
|||
class Color(
|
||||
val red: Int = 0,
|
||||
val green: Int = 0,
|
||||
val blue: Int = 0
|
||||
val blue: Int = 0,
|
||||
) {
|
||||
override fun toString(): String {
|
||||
return "($red, $green, $blue)"
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
import atomictest.eq
|
||||
|
||||
fun main() {
|
||||
val list = listOf(1, 2, 3)
|
||||
val list = listOf(1, 2, 3,)
|
||||
list.toString() eq "[1, 2, 3]"
|
||||
list.joinToString() eq "1, 2, 3"
|
||||
list.joinToString(prefix = "(",
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
// NullableTypes/Task2.kt
|
||||
package nullableTypesExercise2
|
||||
|
||||
// type your solution here
|
||||
// Type your solution here
|
|
@ -1,17 +1,18 @@
|
|||
// Overloading/OverloadedVsDefaultArg.kt
|
||||
package overloadingvsdefaultargs
|
||||
import atomictest.*
|
||||
|
||||
fun foo(n: Int = 99) = print("foo-1-$n")
|
||||
fun foo(n: Int = 99) = trace("foo-1-$n")
|
||||
|
||||
fun foo() {
|
||||
println("foo-2")
|
||||
trace("foo-2")
|
||||
foo(14)
|
||||
}
|
||||
|
||||
fun main() {
|
||||
foo()
|
||||
}
|
||||
/* Output:
|
||||
foo-2
|
||||
foo-1-14
|
||||
*/
|
||||
trace eq """
|
||||
foo-2
|
||||
foo-1-14
|
||||
"""
|
||||
}
|
|
@ -1,10 +1,11 @@
|
|||
// SafeCallsAndElvis/SafeOperation.kt
|
||||
package safecalls
|
||||
import atomictest.*
|
||||
|
||||
fun String.echo() {
|
||||
println(this.toUpperCase())
|
||||
println(this)
|
||||
println(this.toLowerCase())
|
||||
trace(this.toUpperCase())
|
||||
trace(this)
|
||||
trace(this.toLowerCase())
|
||||
}
|
||||
|
||||
fun main() {
|
||||
|
@ -12,9 +13,9 @@ fun main() {
|
|||
s1?.echo() // [1]
|
||||
val s2: String? = null
|
||||
s2?.echo() // [2]
|
||||
}
|
||||
/* Output:
|
||||
HOWDY!
|
||||
Howdy!
|
||||
howdy!
|
||||
*/
|
||||
trace eq """
|
||||
HOWDY!
|
||||
Howdy!
|
||||
howdy!
|
||||
"""
|
||||
}
|
|
@ -851,6 +851,11 @@ public class TestAllExamples extends AbstractTestExamples {
|
|||
testExample("Introduction to Objects/Summary 2/Examples/src/ColorSet.kt", summary2.ColorSetKt::main);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUsingTrace() {
|
||||
testExample("Introduction to Objects/Summary 2/Examples/src/UsingTrace.kt", UsingTraceKt::main);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPropertyReadWrite() {
|
||||
testExample("Introduction to Objects/Summary 2/Examples/src/PropertyReadWrite.kt", summary2.PropertyReadWriteKt::main);
|
||||
|
@ -1621,6 +1626,11 @@ public class TestAllExamples extends AbstractTestExamples {
|
|||
testExample("Functional Programming/Folding Lists/Examples/src/FoldVsForLoop.kt", FoldVsForLoopKt::main);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRunningFold() {
|
||||
testExample("Functional Programming/Folding Lists/Examples/src/RunningFold.kt", RunningFoldKt::main);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCallStack() {
|
||||
testExample("Functional Programming/Recursion/Examples/src/CallStack.kt", recursion.CallStackKt::main);
|
||||
|
@ -2296,6 +2306,11 @@ public class TestAllExamples extends AbstractTestExamples {
|
|||
testExample("Power Tools/Scope Functions/Examples/src/NameTag.kt", scopefunctions.NameTagKt::main);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDifferences() {
|
||||
testExample("Power Tools/Scope Functions/Examples/src/Differences.kt", scopefunctions.DifferencesKt::main);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSpeakers() {
|
||||
testExample("Power Tools/Creating Generics/Examples/src/Speakers.kt", creatinggenerics.SpeakersKt::main);
|
||||
|
@ -2411,6 +2426,11 @@ public class TestAllExamples extends AbstractTestExamples {
|
|||
testExample("Power Tools/Operator Overloading/Examples/src/DefaultEquality.kt", operatoroverloading.DefaultEqualityKt::main);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInvokeFunctionType() {
|
||||
testExample("Power Tools/Operator Overloading/Examples/src/InvokeFunctionType.kt", operatoroverloading.InvokeFunctionTypeKt::main);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEqualsForNullable() {
|
||||
testExample("Power Tools/Operator Overloading/Examples/src/EqualsForNullable.kt", operatoroverloading.EqualsForNullableKt::main);
|
||||
|
|
Loading…
Reference in New Issue