import khoury.EnabledTest import khoury.runEnabledTests import khoury.testSame // value "r" refers to a new object, // an instance of the class IntRange // that has been "constructed" with values // start=1, endInclusive=5 val r = IntRange(1, 5) // same as 1..5 println(r) // this object has member data that can be accessed println(r.start) println(r.endInclusive) // this object also has member functions, that can // work with its own data // think: toList(r) // sum(r) println(r.toList()) println(r.sum()) // and even arguments you supply // think: contains(r, 3) println(r.contains(3)) println(r.contains(10)) // just the data of [start, endInclusive] data class MyIntRangeData(val start: Int, val endInclusive: Int) // function to convert to a list fun intRangeDataToList(myIR: MyIntRangeData): List { val rangeSize = myIR.endInclusive - myIR.start + 1 return List(rangeSize) { myIR.start + it } } val myRD = MyIntRangeData(1, 5) println(intRangeDataToList(myRD)) // represents the integer range of [start, endInclusive] data class MyIntRange(val start: Int, val endInclusive: Int) { // produces the number of numbers in the range fun count(): Int { // unnecessary `this`, for demonstration return this.endInclusive - this.start + 1 } // converts to a list fun toList(): List { return List(count()) { start + it } } // adds up the values in start..endInclusive // this will become WAY easier next week ;) fun sum(): Int { return toList().fold(0) { acc, num -> acc + num } } // determines if a supplied number is in the range fun contains(num: Int): Boolean { return (num >= start) && (num <= endInclusive) } } @EnabledTest fun testMyIntRange() { fun helpTest( start: Int, endInclusive: Int, containsNums: List, ) { val mine = MyIntRange(start, endInclusive) val compare = start..endInclusive testSame( mine.count(), compare.count(), "count: $compare" ) testSame( mine.toList(), compare.toList(), "toList: $compare", ) testSame( mine.sum(), compare.sum(), "sum: $compare", ) containsNums.forEach { testSame( mine.contains(it), compare.contains(it), "contains($it): $compare", ) } } helpTest(0, 3, listOf(0, 1, 3, 5, 6)) helpTest(1, 5, listOf(0, 1, 3, 5, 6)) helpTest(10, 20, listOf(9, 10, 15, 20, 21)) } fun main() { } runEnabledTests(this) main()