What does it mean to be "Kotlin First"?
How can you start taking full advantage of Kotlin for Android development?
Kotlin FirstTaking Full Advantage of Kotlin for Android DevelopmentANDROID DEVELOPER@n8ebel www.goobar.ioNate Ebel
View Slide
KotlinFirst
How can we take full advantage of Kotlin?
Taking Full Advantage of KotlinMigratingJavaSyntax&FeaturesKotlin Standard LibraryCoroutines&FlowJetpackComposeKotlinMultiplatform
Taking Full Advantage of KotlinNew To Kotlin Kotlin Practitioner Kotlin Veteran
The Kotlin Journey
How do I start?Am I doing this right?I’m convincedI love Kotlin
Taking Full Advantage of KotlinGet Started With Kotlin Idiomatic KotlinGoing Full Kotlin Kotlin Beyond Android
Taking Full Advantage of KotlinIdiomatic KotlinGoing Full Kotlin Kotlin Beyond AndroidNew ProjectsConverting JavaExperimentation
Taking Full Advantage of KotlinGoing Full Kotlin Kotlin Beyond AndroidNew ProjectsConverting JavaExperimentationSyntaxKotlin Standard LibraryLanguage Features
Taking Full Advantage of KotlinKotlin Beyond AndroidNew ProjectsConverting JavaExperimentationSyntaxKotlin Standard LibraryLanguage FeaturesAndroid JetpackCoroutines/FlowBuildscripts/Libraries
Taking Full Advantage of KotlinNew ProjectsConverting JavaExperimentationSyntaxKotlin Standard LibraryLanguage FeaturesAndroid JetpackCoroutines/FlowBuildscripts/LibrariesKotlin MultiplatformServer-side KotlinKotlin Scripting
Taking Advantage of Kotlin for Android Development
Getting Started With KotlinHow do I start?
Create A New AndroidStudio Project
Convert Existing Java to Kotlin
Paste Java Into aKotlin File
Quickly Evaluate Kotlin Code
Quickly Evaluate Kotlin Code•Kotlin scratch files•Kotlin REPL•Add a main() function
Idiomatic KotlinAm I doing this right?
Useful Syntax
Useful Syntax•Use non-null types•Avoid #!!•Use lateinit var•Utility functions without classes
Kotlin Standard Library
• arrayOf() / listOf() / mapOf()• filter()• map()• orEmpty()• getOrElse()• isNullOrEmpty() / isNullOrBlank()Kotlin Standard Library
val awesomeThings = listOf("360AnDev", null, "Kotlin")
val awesomeThings = listOf("360AnDev", null, "Kotlin").filterNotNull()
val awesomeThings = listOf("360AnDev", null, "Kotlin").filterNotNull().filter { it.length > 6 }
val awesomeThing = listOf("360AnDev", null, "Kotlin").filterNotNull().filter { it.length > 6 }.getOrElse(0) { "There were no awesome things longer than 6 chars"}
val awesomeThing = listOf("360AnDev", null, "Kotlin").filterNotNull().filter { it.length > 6 }.getOrElse(0) { "There were no awesome things longer than 6 chars"}.let { AwesomeThing(it) }
Special LanguageFeatures
• Data classes• Sealed classes• Extension functionsSpecial Language Features
data class Repo(val name: String,val owner: Owner,val stars: Int)Data Classes
sealed class ViewState {object Loading : ViewState()data class Error(val error: Throwable?)data class Success(val data: List)}Sealed Classes
fun Context.longToast(msg: String) {Toast.makeText(this, msg, Toast.LENGTH_LONG).show()}Extension Functions
Going Full KotlinKotlin all the things!
Android Jetpack
Android Jetpack•Paging 3•Benchmark•Android KTX
Android KTX
Kotlin extensions for JetpackLeverage Kotlin features•Extension functions/properties•Lambdas•CoroutinesAndroid KTX
sharedPreferences.edit {putString(“key”, “with KTX”)putBoolean(“lessBoilerplat”, true)}KTX Core
fragmentManager().commit {addToBackstack(“#..”)add(…)}Fragment KTX
val viewState: LiveData = liveData {emit(defaultViewState())} LiveDate KTX
@Query(“SELECT * FROM Repos”)suspend fun getRepos(): List@Query(“SELECT * FROM Repos”)Fun getRepos(): Flow>Room KTX
Class RepoListViewModel : ViewModel() {init {viewModelScope.launch {#// load async data}}}ViewModel KTX
Kotlin Coroutines
Coroutines are therecommended solution forasync programming onAndroid
@UiThreadsuspend fun showTasks() {val tasks = loadTasksFromDisk()displayTasks(tasks)}suspend fun loadTasksFromDisk: List
Class TaskListViewModel : ViewModel() {init {viewModelScope.launch {showTasks()}}}
interface TasksApi {@GET(“/tasks/user”)suspend fun loadTasksForUser(id: String)}
Class TaskListViewModel : ViewModel() {init {viewModelScope.launch {showTasks()val networkTasks = loadTasksForUser()}}}
Kotlin Flow
A Flow is an async datastream leveragingcoroutines
@Query(“SELECT * FROM Repos”)fun getRepos(): Flow>
val repos: LiveData> = repoDao.getRepos().asLiveData()
class TaskListViewModel : ViewModel() {private val _viewState = MutableStateFlow(ViewState())val viewState: StateFlow = _viewState}
Gradle Kotlin DSL
import org.jetbrains.kotlin.config.KotlinCompilerVersionplugins {id(“com.android.application”)kotlin(“android”)kotlin(“android.extensions”)}android {compileSdkVersion(29)…}dependencies {iplementation(“com.android.support:appcompat-v7:27.1.1”)}build.gradle.kts
Jetpack Compose
Jetpack Compose is thefuture of UI developmentfor Android
@Composablefun HelloWorld() {Test(“Hello World”)}
@Composablefun RepoItem() {Column {Text(“repo name”)Text(“repo owner”)}}
class MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContent {RepoItem()}}}
Bonus• Koin• SQLDelight• Moshi• Coil• MockK
Kotlin Beyond AndroidWhat else can I build with Kotlin?
Kotlin Multiplatform
Share core logicacross platforms usingKotlin Multiplatform
Kotlin MultiplatformWrite common Kotlin codePackage/Consume for multiple targets•Android/JVM•iOS/MacOS•JavaScript•Native
Kotlin MultiplatformDoes not replace native UIRelatively low risk for Android
Server Side Kotlin
Server Side KotlinMultiple supported frameworks•Ktor•Spring Boot•Quarkus
fun main(args: Array) {val server = embeddedServer(Netty, 8080) {routing {get(“/“) {call.respondText(“Hello World!”, ContentType.Text.HTML)}get(“/tasks”) {#// return tasks}}}server.start(wait = true)}Simple Ktor service
More Kotlin
More KotlinAdditional ways to use Kotlin•JavaScript•Kotlin Native•Kotlin scripting using script
Taking Full Advantage of KotlinProject Samples & DefaultsLibraries &ToolingRecommendedLanguage &PatternsUsefulnessBeyondAndroid
ANDROID DEVELOPER@n8ebel www.goobar.ioNate EbelThanks for Watching