Update 01.04.2022

This commit is contained in:
Alexander Nozik 2022-04-01 19:57:32 +03:00
parent cbfecbb8ad
commit e4783ca9e2
19 changed files with 168 additions and 17 deletions

View File

@ -1,5 +1,5 @@
plugins { plugins {
kotlin("jvm") version "1.4.32" kotlin("jvm") version "1.6.10"
} }
group = "ru.mipt.npm" group = "ru.mipt.npm"

View File

@ -0,0 +1,15 @@
package demos
import java.io.IOException
fun main() {
try {
val b: Nothing = throw RuntimeException("Oops")
} catch (t: IOException){
println(t.message + "_io")
} catch (t: RuntimeException){
println(t.message)
} finally {
println("caught")
}
}

View File

@ -0,0 +1,22 @@
package demos
import java.nio.file.Files
import java.nio.file.Path
import kotlin.io.path.readLines
import kotlin.io.path.useLines
import kotlin.io.path.writeLines
fun main() {
val myFile: Path = Files.createTempFile("ks_demo", ".txt")
myFile.writeLines((0..1000).map { it.toString() })
println(myFile)
val sum: Double = myFile.useLines {
it.drop(10).take(10).map { line ->
line.toDouble()
}.sum()
}
println(sum)
}

View File

@ -0,0 +1,28 @@
package demos
import kotlin.math.PI
import kotlin.math.cos
import kotlin.math.pow
import kotlin.math.sin
fun integrate(range: ClosedRange<Double>, nPoints: Int = 100, f: (Double) -> Double): Double {
val points = DoubleArray(nPoints) { i ->
range.start + i * (range.endInclusive - range.start) / (nPoints - 1)
}
return points.sumOf { f(it) } * (range.endInclusive - range.start) / nPoints
}
fun ((Double) -> Double).integrate(
range: ClosedRange<Double>,
nPoints: Int = 100,
): Double = integrate(range, nPoints, this)
fun main() {
val res = integrate(0.0..PI, 500) { x -> sin(x) + cos(x) * x.pow(2) }
println(res)
val f = { x: Double -> sin(x) + cos(x) * x.pow(2) }
val res2 = f.integrate(0.0..PI)
}

View File

@ -0,0 +1,9 @@
package demos
fun function(array: DoubleArray): DoubleArray {
return DoubleArray(array.size) { i -> array[i] + 1 }
}
fun main() {
println(listOf(1, 2, 3).asSequence().map { it * it }.map { it + 1 }.toList())
}

View File

@ -0,0 +1,9 @@
package demos
fun main() {
val array = doubleArrayOf(1.0, 2.0, 3.0)
val b: Double? = 1.0
val newArray: DoubleArray = DoubleArray(array.size) {
array[it] + (b ?: 0.0)
}
}

View File

@ -18,4 +18,7 @@ fun main() {
/* recommended */ /* recommended */
val sum = (0..20).sum() val sum = (0..20).sum()
val intArray: IntArray = IntArray(20){ it }
intArray.sum()
} }

View File

@ -3,9 +3,10 @@ package lesson2
fun printNotNull(any: Any) = println(any) fun printNotNull(any: Any) = println(any)
val value: Int? = 2 val value: Int? = 2
//val value: Int? by lazy{ 2 }
fun main() { fun main() {
//printNotNull(value) // Error
if (value != null) { if (value != null) {
//not guaranteed to work with mutable variable //not guaranteed to work with mutable variable
printNotNull(value) printNotNull(value)

View File

@ -8,9 +8,16 @@ fun String.countOs(): Int = count { it == 'о' } // implicit this points to Stri
fun main() { fun main() {
fun Int.printMe() = println(this) // explicit this fun Int.printMe() = println(this) // explicit this
"обороноспособность".countOs().printMe() "вылысыпыдыстычка".countOs().printMe()
// listOf(1, 2, 3).odd
// listOf(1, 2.0, 3).odd
} }
//fun doSmth(){
// "вылысыпыдыстычка".countOs().printMe()
//}
/** /**
* Extension property (must be virtual) * Extension property (must be virtual)
*/ */

View File

@ -27,7 +27,7 @@ fun main() {
/** /**
* Using singleton reference without constructor invocation * Using singleton reference without constructor invocation
*/ */
val obj = AnObject val obj: AnInterface = AnObject
/** /**
* Anonymous object * Anonymous object

View File

@ -16,8 +16,8 @@ fun findSomething(): Int {
fun checkCondition(): Int { fun checkCondition(): Int {
fun conditionSatisfied() = false fun conditionSatisfied() = false
if (conditionSatisfied()) { return if (conditionSatisfied()) {
return 1 1
} else { } else {
//error is Nothing //error is Nothing
error("Condition is not satisfied") error("Condition is not satisfied")

View File

@ -28,7 +28,7 @@ fun main() {
println("a = $a, b= $b, c = $c") println("a = $a, b= $b, c = $c")
} }
//Using `let` to compose result. Not recommended to use without a need //Using `let` to compose result. Not recommended using without a need
val letResult = getAClass()?.let { arg -> val letResult = getAClass()?.let { arg ->
arg.c + arg.a arg.c + arg.a
} }

View File

@ -18,6 +18,7 @@ fun main() {
fun getAndIncrement() = i.also { i += 1 } fun getAndIncrement() = i.also { i += 1 }
println(getAndIncrement()) println(getAndIncrement())
println(i)
/** /**
* Configure properties of an object (apply) * Configure properties of an object (apply)

View File

@ -1,5 +1,7 @@
package lesson3 package lesson3
import java.util.ArrayList
/** /**
* Lists and mutable lists * Lists and mutable lists
*/ */
@ -14,7 +16,7 @@ fun main() {
/** /**
* This one creates a mutable list * This one creates a mutable list
*/ */
val mutableList = mutableListOf("a", "b", "c") val mutableList: MutableList<String> = mutableListOf("a", "b", "c")
mutableList[2] = "d" mutableList[2] = "d"
mutableList.add("e") mutableList.add("e")
mutableList += "f" mutableList += "f"
@ -23,17 +25,17 @@ fun main() {
/** /**
* This one creates a mutable ArrayList. * This one creates a mutable ArrayList.
*/ */
val arrayList = arrayListOf("a", "b", "c") val arrayList: ArrayList<String> = arrayListOf("a", "b", "c")
//Danger zone //Danger zone
val newList = list + "f" + mutableList val newList: List<String> = list + "f" + mutableList
println(newList) println(newList)
//Bonus //Bonus
val lambdaList = List(3){it.toString()} val lambdaList = List(3){ it.toString() }
println(lambdaList) println(lambdaList)
} }

View File

@ -1,17 +1,25 @@
package lesson3 package lesson3
fun main() { fun main() {
val map = HashMap<String,String>() val map = mutableMapOf(
"key" to "a",
"key2" to "b",
)
//The map could be accessed via indexing operation //The map could be accessed via indexing operation
println(map["key"]) println(map["key"])
map["key"] = "fff" map["key"] = "fff"
//val entry: MutableMap.MutableEntry<String, String> = map.iterator().next()
/** /**
* The destructuring declaration for maps and other objects that support `operator fun componentN` * The destructuring declaration for maps and other objects that support `operator fun componentN`
*/ */
for ((k, v) in map) { for ((k, v) in map) {
//val (k, v) = entry
// val k = entry.component1()
// val v = entry.component2()
println("$k -> $v") println("$k -> $v")
} }
@ -22,4 +30,8 @@ fun main() {
val coord = doubleArrayOf(0.0, 1.0, 2.0) val coord = doubleArrayOf(0.0, 1.0, 2.0)
val (x,y,z) = coord val (x,y,z) = coord
data class Coordinate(val x: Double, val y: Int)
val (x1, y1) = Coordinate(1.0,2)
} }

View File

@ -1,6 +1,9 @@
package lesson3 package lesson3
class AClassWithList{ class AClassWithList{
var b: Double = 2.0
private set
private val _list = ArrayList<Int>() private val _list = ArrayList<Int>()
val list: List<Int> get() = _list val list: List<Int> get() = _list
} }

View File

@ -1,5 +1,11 @@
package lesson3 package lesson3
import java.time.Instant
class DateRange(val start: Instant, val end: Instant)
operator fun DateRange.contains(value: Instant): Boolean = value > start && value < end
fun main() { fun main() {
val emailsList = emptyList<String>() val emailsList = emptyList<String>()
@ -15,11 +21,41 @@ fun main() {
println("not in list") println("not in list")
} }
println(Instant.now() in DateRange(Instant.EPOCH, Instant.MAX))
// Another (different) use of `in` is iteration over range or collection using // Another (different) use of `in` is iteration over range or collection using
// using `operator fun iterator` // using `operator fun iterator`
for (i in 1..100) { println(i) } // closed range: includes 100 for (i in 1..100) {
for (i in 1 until 100) { println(i) } // half-open range: does not include 100 println(i)
for (x in 2..10 step 2) { println(x) } } // closed range: includes 100
for (x in 10 downTo 1) { println(x) }
(1..100).forEach { i ->
println(i)
} //the same, but with boxing
for (i in 1 until 100) {
println(i)
} // half-open range: does not include 100
for (x in 2..10 step 2) {
println(x)
}
for (x in 10 downTo 1) {
println(x)
}
infix fun ClosedRange<Double>.step(step: Double): Sequence<Double> {
//TODO check arguments
var current = start
return sequence {
do {
yield(current)
current += step
} while (current <= endInclusive)
}
}
for (x in 0.0..10.0 step 0.5){
println(x)
}
} }

View File

@ -26,4 +26,5 @@ fun main() {
} }
integrate(0.0, PI) { sin(it) } integrate(0.0, PI) { sin(it) }
integrate(0.0, PI, step = 0.02) { sin(it) } integrate(0.0, PI, step = 0.02) { sin(it) }
//integrate(0.0, step = 0.02, PI) { sin(it) }
} }

View File

@ -6,7 +6,9 @@ fun main() {
val result = list val result = list
.filter { it % 2 == 0 } //select even numbers .filter { it % 2 == 0 } //select even numbers
.map { it * it } // get square of each element .map { it * it } // get square of each element
.sumByDouble { it.toDouble() } //use one of reduce operations //.onEach { println(it) }
//.sumOf { it } //use one of reduce operations
.reduce { acc, i -> acc + i }
println(result) println(result)
} }