This commit is contained in:
Alexander Nozik 2021-03-18 15:55:42 +03:00
parent ddfd17de81
commit 68c7884464
7 changed files with 148 additions and 0 deletions

View File

@ -0,0 +1,32 @@
package lesson2
import java.io.File
/**
* idiom 10
* Nullable truth.
*/
fun idiom10() {
class A(val b: Boolean?)
val a: A = A(null)
//use
a?.b == true
//instead of
a?.b ?: false
}
/**
* Dart-like (?=) nullable assignment
*/
fun idiom11(){
var x: String? = null
x = x ?: "Hello"
}
/**
* Safe call and elvis operator
*/
fun idiom12(){
val files = File("Test").listFiles()
println(files?.size ?: "empty")
}

View File

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

View File

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

View File

@ -0,0 +1,44 @@
package lesson2
//Interfaces and objects
interface AnInterface {
fun doSomething()
}
class AClass : AnInterface {
override fun doSomething() = TODO()
}
/**
* A singleton (object) is a type (class) which have only one instance
*/
object AnObject : AnInterface {
override fun doSomething(): Unit = TODO("Not yet implemented")
}
fun main() {
/**
* Creating an instance
*/
val instance = AClass()
/**
* Using singleton reference without constructor invokation
*/
val obj = AnObject
/**
* Anonymous object
*/
val anonymous = object : AnInterface {
override fun doSomething(): Unit = TODO("Not yet implemented")
}
/**
* The one that should not be named
*/
val voldemort = object {
fun doSomething(): Unit = TODO()
}
}

View File

@ -0,0 +1,11 @@
package lesson2
/**
* Matching by type
*/
fun checkType(arg: Any) = when(arg){
is String -> println("I am a String")
is Int -> println("I am an Int")
is Double -> println("I am a Double")
else -> println("I don't know who am I?")
}

View File

@ -0,0 +1,12 @@
package lesson2
class SimpleClass(val a: Int, val b: Double)
data class DataClass(val a: Int, val b: Double)
fun main() {
val data = DataClass(2, 2.0)
val copy = data.copy(b = 22.2)
println(copy)
}

View File

@ -0,0 +1,23 @@
package lesson2
/**
* The declaration if valid because [TODO] returns Nothing
*/
fun getSomething(): Int? = TODO()
fun findSomething(): Int {
// early return is valid because `return` operator result is Nothing
val found = getSomething() ?: return 2
return found + 2
}
fun checkCondition(): Int {
fun conditionSatisfied() = false
if (conditionSatisfied()) {
return 1
} else {
//error is Nothing
error("Condition is not satisfied")
}
}