-
Advantages over java
- no boilperate
-
Origin of Kotlin
-
By jetbrains
-
Prgmatic, Concise, Safe and Interoperatable
-
Better functional support than java8
-
Kotlin is more about getting the things done
-
Not religious about functional programming
-
Kotlin is 'better' java
-
Well suited to write DSL
-
-
Basics
-
val is immutable and var is immutable
-
Static typing with type inference
-
Language brevity like multiple constructors
-
fun main(args: Array) {
var numbers = arrayOf(1,2,3,4,5)
var sum = 0
for (i in numbers)
sum+=i
println(sum)
}
Default Arguments and named parameters
fun fullName(firstName: String = "bob", secondName: String=""): String {
return "$firstName $secondName"
}
fun main(args: Array) {
println(fullName("s","s"))
fullName(firstName= "John", secondName= "Doe")
}
Nullable
fun lengthOfNullable(s: String?): Int? = s?.length ?:0
fun main() {
println(lengthOfNullable("Hello"))
println(lengthOfNullable(null))
}
?:0
LVS operator
When
fun whenDemo(obj: Any){
when(obj){
1 -> println("One")
2,4 -> println("Two or Four")
in 6..10 -> println("Between 6 and 10")
is String -> println("A string with length ${obj.length}")
is List<*> -> println(obj)
else -> println("Something else")
}
}
fun main(args: Array) {
whenDemo("hello")
whenDemo(1)
whenDemo(listOf("one", "two"))
}
Code smells
-
feature envy
- Move to proper class
-
Replace temp with query
-
Inline Variables
-
Long method
-
Perfomence tradeoffs
-
Yagni
-
Law of delimeter
-
map, fold, reduce, groupBy
-
names .map{it.toLowerCase()} .reduce{acc, s -> "$acc$s"} .toCharArray() .groupBy{it} .map{(char, charList)-> Pair(char, charList.size)}
Imperative vs Declarative Style of doing things
-
Anemeic domain models vs Rich domain model
-
Higher order functions
-
Kotlin is not oponiated about functional programming
-
Need not to be functional
-
But almost alll libraries follow functional
-
Async non blocking with back pressure
-
Use cases
-
Live feed
-
Stock market watch
-
Fraud detection in finance
-
A micro service that talks to other services
-
-
Async stream processing
-
Non blocking
-
Eg Tomcat
-
Multi threded vs blocking
-
Context switching penalty of multi threading
-
ngnix use event bus and it scales well
-
-
Back pressure
- The capability of a component under stress to inform other components that it is under pressure
-
Reactive Manifesto
-
Provide an interface/Sepcification
-
Eg: RxJava, Reactor
-
Publisher and Subscriber
-
Spring use reactor internally
-
-
Reactive stream
-
Flux vs Mono
-
Cold observable
-
publisher.subscribe(object: Subscriber{})
fun main() {
val elements = mutableListOf()
val publisher = Flux.just(1,2,3)
publisher.subscribe(object: Subscriber{
override fun onComplete() {
}
override fun onSubscribe(s: Subscription) {
s.request(Long.MAX_VALUE)
}
override fun onNext(t: Int) {
elements.add(t)
}
override fun onError(t: Throwable?) {
}
})
println(elements)
}
-
Function pipeline
-
Lazy evaluation