Kotlin Spring
Kotlin Spring
Using
Spring Boot and Kotlin
Dilip
About Me
• Dilip
• Any Java Developer who is interested in learning Kotlin can enroll in this
course
• This is free and open source language licensed under Apache 2.0
Who uses Kotlin ?
Why Kotlin ?
• Kotlin is an expressive language and it has a concise syntax
• Web Applications
• RestFul Services
• Messaging Applications
Kotlin
*.kt *.class .jar
Compiler
Java Runtime
Environment
Kotlin/Java Build Process
Kotlin
*.kt *.class .jar
Compiler
Java Runtime
Java
*.java *.class .jar Environment
Compiler
val & var
• Any variable in Kotlin should be declared as val or var
• val
• Variables declared with val are immutable variables
val name : String = "Dilip"
• var
• Variables declared with var are mutable variables
var age : Int = 33
fun printHello(){
}
Functions with No return value
• Functions wit no return value are represented as Unit in Kotlin
fun addition(x: Int, y : Int) : Int { fun addition(x: Int, y : Int) = x+y
return x+y
}
fi
Default Value Parameters
&
Named Arguments
Default Value Parameters
• This provides a default value to a function parameter when its not passed by
the caller
println("Name is $name and the email is $email and the dob is $dob")
}
Named Arguments
• The caller can invoke the function by using the variable name
fun printPersonDetails(name : String, email : String = "",
dob : LocalDate = LocalDate.now()){
println("Name is $name and the email is $email and the dob is $dob")
}
• Caller can invoke the function using the name of the function arguments, in no particular order
printPersonDetails(dob = LocalDate.parse("2000-01-01") , name = "Dilip", email =
"[email protected]")
Top Level
Functions & Properties
Top Level Functions
• Functions that does not belong to a class are top-level functions
• In Java applications, you can nd classes that just has some static methods
which holds some common logic that can be used across the app
• Kotlin avoids this by using top level functions that can be part of a Kotlin le
not a class
fi
fi
Top Level Properties
• In Kotlin, properties that does not belong to class are called top-level
properties
person.action()
Constructors in Kotlin
Constructors in Kotlin
• Constructors is a concept in object oriented programming through which we
can create an Object with initial values
1
class Person(val name: String,
val age: Int) { Primary Constructor
2
fun action() {
println("Person Walks")
}
}
class Item(){
var name : String = ""
constructor(_name : String) : this(){
name = _name
}
}
• constructor keyword
• this() call to the actual class is
mandatory
fi
Recommended approach for constructors
• Use Primary Constructors whenever possible
fun action() {
println("Person Walks")
}
}
Use Secondary Constructors only necessary
Initializer code using init block
• init code block can be used to run some initialization logic during the instance
creation
init {
}
data class
• Classes just holds the data can be categorized as data classes
• DTOs, domain classes and value object classes fall under this category
• In Java, these type of classes are also Java Beans
data class Course(
val id: Int,
val name: String,
val author: String
)
• It autogenerates a lot of functionalities for you when you add the data
modi er to the class
• Its pretty easy to create a clone of the object using the copy( ) function
fi
When to use Custom Getter/Setter ?
• Kotlin Concepts:
fi
Inheritance - Overriding Functions
• Mark the function with open modi er
open class User(val name: String) {
}
}
class Student(name: String): User(name, age) {
super.login()
}
object keyword
• This keyword allows us to create a class and an instance of the class at the
same time
} • Limitations
Authenticate.authenticate("Dilip", "abc")
}
companion object
• Kotlin does not have the support for the static keyword
• companion object can be used to introduce static functionalities that are tied
to the class.
}
Interface
• Interfaces in oops de nes the contract which has some abstract methods
}
Visibility Modifiers
in
Kotlin
Visibility Modifiers in Kotlin
• There are four visibility modi ers in Kotlin :
• public, protected, private and internal
• public
• This is the default access modi ers
• private
• This marks the function or variable accessible only to that class
• protected
• A protected member is visible in the class and subclass
• internal
• This is new in Kotlin. Anything that’s marked with internal is private to the module that’s
published using the Gradle or Maven
fi
fi
Type Checking & Casting
• Kotlin has some handy operators
• is operator
• Check a particular value is of a certain type
val name = “Dilip"
Or
null value is not allowed
Or
• Use the safe call • Return a Default • Making sure the value
operator to invoke value if null is not null after some
functions safely on it updates
val movie =
val length = nameNullable?.length val length = nameNullable?.length ?: 0 saveMovie(Movie(null,
“Avengers”))
println(movie.id!!)
Collections in Kotlin
Collections
• Kotlin re-uses the collections from Java
• Mutable Collections
• Immutable Collections
Immutable Collection Mutable Collection
• Collection is not modi able once • Modifying the data in the collection
created is allowed
val names = listOf("Alex", "Ben", “Chloe") val namesMutableList = mutableListOf(“Alex",“Ben", "Chloe")
Map
mapOf("dilip" to 33 ,"scooby" to 4) mutableMapOf("dilip" to 33 ,"scooby" to 4)
Set
setOf("adam", "ben", "chloe") mutableSetOf("adam", "ben", "chloe")
fi
What is a Lambda Expression ?
• Lambda Expressions are small piece of code that can be passed to other
functions
• The advantage here is that , you can pass the lambda as an argument to
other functions
listOf(1, 2, 3)
.forEach {
val result = add(it)
println(result)
}
2 4 6
Collections & Operations on it
• Using Collections are very common in any application development
val result = list.map { outerList -> val result = list.flatMap { outerList ->
outerList.map {
outerList.map {
it.toDouble() it.toDouble()
}
}
} }
println("result : $result")
println("result : $result")
result : [ [1.0, 2.0, 3.0], [4.0, 5.0, 6.0] ] result : [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
fl
fl
Lazy Evaluation of Collections using Sequences
• This is an alternative API to work with collections
• The operations on the elements of the collection are evaluated lazily
Not a sequence sequence
Terminal Operator
Whats the benefit of using Sequences ?
• Sequences perform better when dealing with collections that are extremely
big
• Exceptions are handled pretty much the standard way using the try-catch
block
if(nameNullable!=null){
var nameNullable : String? = null
printName(nameNullable)
nameNullable?.run {
println(“Completed!")
printName(this)
}
println(“Completed!")
}
Scope Function accepts the lambda
Overview of the Application
• Build a Course Catalog Service
• RestFul API that manages the
course catalog for an online
learning platform
Course Catalog
• Use DB for storing the course Service
DB
Information
Automated Testing
Using JUnit5
Automated Tests
• Automated Tests plays a vital role in delivering quality Software
• Integration Tests
• Unit Tests
Integration Tests
• Integration test is a kind of test which actually test the application end
to end
1 2 3
Integration
Controller Service Repository DB
Test
Unit Tests
• Unit test is a kind of test which tests only the class and method of interest
and mocks the next layer of the code
CourseEntity
JSON
Course Catalog
Client DB
Service
CourseDTO
Course Catalog Service
Course Catalog
Client DB
Service
Postgres
H2
JVM related Kotlin Annotations
• @JvmOverloads - This is used to instruct the JVM to create the overloaded
version of methods when dealing with default values
• @JvmField - This is used to instruct the JVM to create the variable as a eld
• @JvmName - This is used to instruct the JVM to create a custom name for a
class or function
fi