lesson 3 update
This commit is contained in:
parent
967c5b0155
commit
6631dba59b
@ -6,6 +6,8 @@ object AClass{
|
||||
val c = "c"
|
||||
}
|
||||
|
||||
fun getAClass(): AClass? = null
|
||||
|
||||
/**
|
||||
* [with]/[run]/[let] are used to create a scope with given argument or receiver
|
||||
*/
|
||||
@ -14,20 +16,20 @@ fun main() {
|
||||
println("a = ${AClass.a}, b= ${AClass.b}, c = ${AClass.c}")
|
||||
|
||||
// Using `with`
|
||||
with(AClass){
|
||||
val res = with(AClass){
|
||||
// AClass type is the receiver in this scope
|
||||
println("a = $a, b = $b, c = $c")
|
||||
return@with "some value"
|
||||
}
|
||||
|
||||
//using `run`
|
||||
AClass.run {
|
||||
getAClass()?.run {
|
||||
// the same as above
|
||||
println("a = $a, b= $b, c = $c")
|
||||
}
|
||||
|
||||
//Using `let` to compose result. Not recommended to use without a need
|
||||
val letResult = AClass.let {
|
||||
it.c + it.a
|
||||
val letResult = getAClass()?.let { arg ->
|
||||
arg.c + arg.a
|
||||
}
|
||||
}
|
@ -17,6 +17,8 @@ fun main() {
|
||||
*/
|
||||
fun getAndIncrement() = i.also { i += 1 }
|
||||
|
||||
println(getAndIncrement())
|
||||
|
||||
/**
|
||||
* Configure properties of an object (apply)
|
||||
* https://kotlinlang.org/docs/idioms.html#configure-properties-of-an-object-apply
|
||||
|
@ -29,9 +29,12 @@ fun main() {
|
||||
|
||||
val newList = list + "f" + mutableList
|
||||
|
||||
println(newList)
|
||||
|
||||
//Bonus
|
||||
|
||||
val lambdaList = List(3){it.toString()}
|
||||
println(lambdaList)
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -15,5 +15,11 @@ fun main() {
|
||||
println("$k -> $v")
|
||||
}
|
||||
|
||||
map.forEach { (k, v) -> println("$k -> $v")}
|
||||
|
||||
val (a, b) = Pair(1, 2)
|
||||
|
||||
val coord = doubleArrayOf(0.0, 1.0, 2.0)
|
||||
|
||||
val (x,y,z) = coord
|
||||
}
|
@ -7,5 +7,5 @@ class AClassWithList{
|
||||
|
||||
fun main() {
|
||||
val obj = AClassWithList()
|
||||
|
||||
obj.list
|
||||
}
|
@ -1,13 +1,17 @@
|
||||
@file:JvmName("Idiom26Kt")
|
||||
|
||||
package lesson3
|
||||
|
||||
import kotlin.math.PI
|
||||
import kotlin.math.sin
|
||||
|
||||
fun main() {
|
||||
fun integrate(from: Double = 0.0, to: Double = 1.0, step: Double = 0.01, function: (Double) -> Double): Double {
|
||||
fun integrate(
|
||||
from: Double = 0.0,
|
||||
to: Double = 1.0,
|
||||
step: Double = 0.01,
|
||||
function: (Double) -> Double,
|
||||
): Double {
|
||||
require(to > from)
|
||||
require(step > 0)
|
||||
var sum = 0.0
|
||||
var pos = from
|
||||
while (pos < to) {
|
||||
@ -17,7 +21,9 @@ fun main() {
|
||||
return sum
|
||||
}
|
||||
|
||||
integrate { x -> x * x + 2 * x + 1 }
|
||||
integrate { x ->
|
||||
x * x + 2 * x + 1
|
||||
}
|
||||
integrate(0.0, PI) { sin(it) }
|
||||
integrate(0.0, PI, step = 0.02) { sin(it) }
|
||||
}
|
Loading…
Reference in New Issue
Block a user