lesson 2 update

This commit is contained in:
Alexander Nozik 2021-03-19 18:39:14 +03:00
parent c5cba1d716
commit 78141cf98e
8 changed files with 43 additions and 14 deletions

View File

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

View File

@ -8,17 +8,29 @@ import java.io.File
*/
fun idiom10() {
class A(val b: Boolean?)
val a: A = A(null)
val a: A? = A(null)
//use
a?.b == true
//instead of
a?.b ?: false
// The old way
val res = if (a == null) {
false
} else {
if (a.b == null) {
false
} else {
a.b
}
}
}
/**
* Dart-like (?=) nullable assignment
*/
fun idiom11(){
fun idiom11() {
var x: String? = null
x = x ?: "Hello"
}
@ -26,7 +38,7 @@ fun idiom11(){
/**
* Safe call and elvis operator
*/
fun idiom12(){
fun idiom12() {
val files = File("Test").listFiles()
println(files?.size ?: "empty")
}

View File

@ -2,14 +2,16 @@ package lesson2
fun printNotNull(any: Any) = println(any)
fun main(){
var value: Int? = 2
val value: Int? = 2
if(value != null){
fun main() {
if (value != null) {
//not guaranteed to work with mutable variable
printNotNull(value)
}
// Safe call here
value?.let {
printNotNull(it) // execute this block if not null
printNotNull(value) // value is not null here

View File

@ -5,9 +5,9 @@ package lesson2
*/
fun String.countOs(): Int = count { it == 'о' } // implicit this points to String
fun Int.printMe() = println(this) // explicit this
fun main() {
fun Int.printMe() = println(this) // explicit this
"обороноспособность".countOs().printMe()
}

View File

@ -3,10 +3,11 @@ package lesson2
//Interfaces and objects
interface AnInterface {
val a: Int get() = 4
fun doSomething()
}
class AClass : AnInterface {
class AClass(override val a: Int) : AnInterface {
override fun doSomething() = TODO()
}
@ -21,10 +22,10 @@ fun main() {
/**
* Creating an instance
*/
val instance = AClass()
val instance = AClass(3)
/**
* Using singleton reference without constructor invokation
* Using singleton reference without constructor invocation
*/
val obj = AnObject
@ -41,4 +42,6 @@ fun main() {
val voldemort = object {
fun doSomething(): Unit = TODO()
}
voldemort.doSomething()
}

View File

@ -8,4 +8,8 @@ fun checkType(arg: Any) = when(arg){
is Int -> println("I am an Int")
is Double -> println("I am a Double")
else -> println("I don't know who am I?")
}
fun main() {
checkType(true)
}

View File

@ -1,11 +1,17 @@
package lesson2
class SimpleClass(val a: Int, val b: Double)
class SimpleClass(val a: Int, val b: Double, c: Double)
data class DataClass(val a: Int, val b: Double)
data class DataClass(val a: Int, val b: Double){
val c get() = b +1
}
fun main() {
val simple = SimpleClass(1,2.0,3.0)
println(simple)
val data = DataClass(2, 2.0)
val copy = data.copy(b = 22.2)
println(copy)

View File

@ -1,5 +1,7 @@
package lesson2
import lesson1.returnUnit
/**
* The declaration if valid because [TODO] returns Nothing
*/