lesson 4 update

This commit is contained in:
Alexander Nozik 2021-04-16 18:34:25 +03:00
parent 868cbc0f50
commit 473cef530e
8 changed files with 29 additions and 9 deletions

View File

@ -1,13 +1,25 @@
package lesson4
class Bad{
open class Bad{
val value: Int
init {
value = requestValue()
}
private fun requestValue(): Int = TODO()
open fun requestValue(): Int {
doSomethingElse()
return 2
}
private fun doSomethingElse(){
println(value)
}
}
fun main() {
Bad()
}

View File

@ -6,7 +6,7 @@ import kotlin.random.Random
fun main() {
val b = Random.nextBoolean()
// assign value to an expression
val a = if (b) 0 else 1
val a = if (b) 0 else 1 // b ? 0 : 1
//Use Try/catch as an exception
val result = try {
@ -14,5 +14,6 @@ fun main() {
} catch (e: NumberFormatException) {
null //Strongly discouraged in performance-critical code
}
println(result)
}

View File

@ -8,4 +8,5 @@ fun main() {
add(it)
}
}
println(list)
}

View File

@ -6,7 +6,7 @@ import java.nio.file.Paths
fun main() {
val stream = Files.newInputStream(Paths.get("/some/file.txt"))
// The resource is automatically closed when leaving the scope
stream.buffered().reader().use { reader ->
stream.bufferedReader().use { reader ->
println(reader.readText())
}
}

View File

@ -1,10 +1,11 @@
package lesson4
import kotlin.random.Random
interface Factory<T : Any> {
fun build(str: String): T
}
class IntContainer(val arg: Int) {
companion object : Factory<IntContainer> {
override fun build(str: String) = IntContainer(str.toInt())
@ -21,4 +22,7 @@ fun <T : Any> buildContainer(str: String, factory: Factory<T>): T = factory.buil
fun main() {
buildContainer("22", IntContainer)
val random = Random
random.nextDouble()
}

View File

@ -4,6 +4,7 @@ class ClassWithALazyProperty{
//Use lazy delegate for something that should be calculated ones on first call
val lazyValue by lazy {
//Do dome heavy logic here
22
}
}

View File

@ -31,6 +31,7 @@ inline fun <reified T: Any> List<T>.prettyPrint() = forEach {
}
/**
* **WARNING** inline functions are an advanced feature and should be used only for reification or non-local return
* **WARNING** inline functions are an advanced feature and should be used only for
* reification or non-local return
* NOT for optimization.
*/

View File

@ -3,14 +3,14 @@ package lesson4
/**
* Values are boxed. Each call is indirect
*/
val list: List<Double> = List(20){it.toDouble()}
val list: List<Double> = List(20) { it.toDouble() }
/**
* Still boxed
*/
val genericArray: Array<Double> = Array(20){it.toDouble()}
val genericArray: Array<Double> = Array(20) { it.toDouble() }
/**
* Non-boxed
*/
val specializedArray: DoubleArray = DoubleArray(20){it.toDouble()}
val specializedArray: DoubleArray = DoubleArray(20) { it.toDouble() }