SlideShare a Scribd company logo
Kotlin for Android
A Real Problem Solver
Hardik Trivedi
Source : https://developers.google.com/events/gdd-india/
Hardik Trivedi
● I am a computer program writer
● Works at Globant, Pune, IN
● An active community speaker
● Co-author of a book "Kotlin Blueprints"
● I love writing tech blogs
● I am mentor for college graduates and
professionals and consultant to companies
About Me
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
Exciting talk and training from Sean @ GDDIndia
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
Day 1: Testing Out Kotlin
Testing is a great way to learn Kotlin, write readable
tests, and introduce your development team to the
power of Kotlin. Learn how to use Kotlin through a deep
dive into writing tests.
Day 2: Taking Advantage of Kotlin in Your Android App
Hands-on experience building Android apps using
Android Studio in the Kotlin language.
Checkout code at https://goo.gl/SyGJ1i
Sean McQuillan
Android Developer
@ Google
Why Kotlin?
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
It’s a Modern
● Type Inference
● First class functions
● Abstraction
● Lambdas
● Extensions
● Coroutines
Why Kotlin?
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
It’s built for Industry
● Not only expressive but keeps Performance in mind
● Readable
● Easy to write scalable code
● It’s targeting JVM, mobile and browsers
● Great tooling support from JetBrains
Why Kotlin?
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
It’s easy to Use
● Interoperability
● Learn in a day
● No surprises
Kotlin announcements
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
● Kotlin 1.2 is out. It has ability to reuse code between JVM and JavaScript
● Kotlin/Native 0.5 is out and it has power calling Kotlin from Swift, C and LLVM 5
● Added a style guide https://android.github.io/kotlin-guides/style.html It has all
the standards Google has used to code in Kotlin
● Added Kotlin/Native support to CLion
● Jetbrains release official Kotlin wrappers to work with React.JS
● Android Lint has support to Kotlin. You can also write custom lint rules for Kotlin.
Kotlin
Basics.inc(){ }
Source : https://developers.google.com/events/gdd-india/
Extension Function
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
val str = "GGDD Extendedd"
fun String.removeFirstLastChar(): String {
return this.substring(1, this.length - 1)
}
str.removeFirstLastChar()// Output is GDD Extended
Extension Function
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
fun View.visible() {
this.visibility = View.VISIBLE
}
fun View.gone() {
this.visibility = View.GONE
}
button.visible()
textView.gone()
Delegated Properties
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
Properties usually contains the direct corresponding value
But Kotlin allows you to delegate some task/behaviour to the properties if managed
properly.
● lazy properties: the value gets computed only upon first access;
● observable properties: listeners get notified about changes to this property;
● storing properties in a map, instead of a separate field for each property.
Delegated Properties - Vetoable
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
class Veto {
var value: String by Delegates.vetoable("String")
{ prop, old, new -> new.contains("GDD") }
}
val veto = Veto()
veto.value = "DevFest"
println(veto.value) // Output String
veto.value="GDD Extended Pune"
println(veto.value) // Output GDD Extended Pune
Semantic Validation
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
Many times we do parameter validation thorough and aggressively
static String join(String sep, List<String> strings) {
if (sep == null) throw new NullPointerException("sep == null");
if (sep.length() < 2) {
throw new IllegalArgumentException("sep.length() < 2");
}
if (strings == null) throw new NullPointerException("strings == null");
...
}
Semantic Validation
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
● With Guava like libraries you can avoid those null checks and manage the pre
conditions gracefully.
● But you don’t add guava for to use only one feature.
● Kotlin avoids nullability by default and it has functions for semantic validations.
fun join(sep: String, strings: List<String>): String {
require(sep.length < 2) { "sep.length() < 2" }
...
}
Let function
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
Java
String data=null;
if(data!=null) {
// Do something
}
Kotlin
var data: String? = null
data?.let {
// it == data always not null and read only once
}
Let function
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
class Concurrent {
@Volatile var data: String? = null
fun doSomething() {
data?.let {
//data always not null and read only once
}
}
}
Higher-order function
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
A higher-order function is a function that takes functions as parameters, or returns a
function.
fun logExecution(func: () -> Unit) {
Log.d("tag", "before executing func")
func()
Log.d("tag", "after executing func")
}
logExecution({ yourFunction() })
Wow moments
See Kotlin in Action !!!{ }
Source : https://developers.google.com/events/gdd-india/
Wow moments
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
// Possible only if it's Java 8
public interface InterfaceA {
default void defaultMethod(){
System.out.println("Interface A
default method");
}
}
interface ToolbarManager {
fun initToolbar() {
toolbar.inflateMenu(R.menu.main_menu)
toolbar.setOnMenuItemClickListener {
// Your code
true
}
}
}
Java Kotlin
Wow moments
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
Button clickButton = (Button)
findViewById(R.id.clickButton);
clickButton.setOnClickListener( new
OnClickListener() {
@Override
public void onClick(View v) {
***Do what you want with the
click here***
}
});
import
kotlinx.android.synthetic.main.activity_
detail.*
clickButton.setOnClickListener {
***Do what you want with the click
here***
}
Java Kotlin
Wow moments
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
private String readInputStream(InputStream is) throws
Exception {
String line = null;
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = new
BufferedReader(new InputStreamReader(is));
while ((line = bufferedReader.readLine()) != null)
{
sb.append(line);
}
bufferedReader.close();
return sb.toString();
}
val inputAsString =
is.bufferedReader().use
{ it.readText() }
// defaults to UTF-8
Java Kotlin
Wow moments
public class MySingleton {
private static MySingleton myObj;
private MySingleton(){
}
public static MySingleton getInstance(){
if(myObj == null){
myObj = new MySingleton();
}
return myObj;
}
}
object MySingleton {
var num: Int = 0
fun domeSomeThing() {
println("Kotlin is awesome!!!")
}
}
Java Kotlin
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
Wow moments
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
SharedPreferences sharedpreferences =
getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
email.setText(sharedpreferences.getStrin
g(Email, ""));
SharedPreferences.Editor editor =
sharedpreferences.edit();
editor.putString("email",
"trivedi.hardik.11@gmail.com");
editor.apply();
private var email: String by
DelegatedPreference(this, "email", "")
email="trivedi.hardik.11@gmail.com"
txtEmail.text=email
Java Kotlin
Wow moments
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
Movie movie = moviesList.get(position);
holder.title.setText(movie.getTitle());
holder.genre.setText(movie.getGenre());
holder.year.setText(movie.getYear());
Movie movie = moviesList[position]
with(movie) {
holder.title.text=title
holder.genre.text=genre
holder.year.text=year
}
Java Kotlin
Wow moments
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
private class GetWeatherTask extends
AsyncTask<String, Void, Forecast> {
protected Forecast doInBackground(String
zipCode) {
return WeatherAPI().execute(zipCode);
}
protected void onPostExecute(Forecast
result) {
showData(result);
}
}
new GetWeatherTask().execute(380015);
fun loadWeatherData() = async(UI) {
val waiter = bg {
WeatherApi(zipCode).execute() }
showData(waiter.await())
}
Java Kotlin
Wow moments
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
Intent intent = Intent(this,SomeOtherActivity.class)
intent.putExtra("id", 5)
intent.setFlag(Intent.FLAG_ACTIVITY_SINGLE_TOP)
startActivity(intent)
startActivity(intentFor<SomeOtherActivity>("id" to 5).singleTop())
Java
Kotlin
Wow moments
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
return inflater.inflate(R.layout.fragment_update_info, container, false);
}
fun ViewGroup.inflate(@LayoutRes layoutRes: Int, attachToRoot: Boolean = false):
View {
return LayoutInflater.from(context).inflate(layoutRes, this, attachToRoot)
}
parent.inflate(R.layout.my_layout)
parent.inflate(R.layout.my_layout, true)
Java
Kotlin
Wow moments
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
Picasso.with(context).load(R.mipmap.ic_launcher).into(imageView);
fun ImageView.loadUrl(url: String) {
Picasso.with(context).load(url).into(this)
}
imageView.loadUrl("http://....")
Java
Kotlin
Wow moments
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
getSupportFragmentManager().beginTransaction()
.add(R.id.container,DataFragment.newInstance(), "detail")
.addToBackStack()
.commit();
fun AppCompatActivity.addFragment(fragment: Fragment, frameId: Int, backStackTag: String? =
null) {
supportFragmentManager.inTransaction {
add(frameId, fragment)
backStackTag?.let { addToBackStack(fragment.javaClass.name) }
}
}
addFragment(DataFragment.newInstance(), R.id.container, "detail")
Java
Kotlin
Snackbar snackbar = Snackbar
.make(coordinatorLayout, "Welcome to GDD", Snackbar.LENGTH_LONG);
snackbar.show();
inline fun View.snack(message: String, length: Int = Snackbar.LENGTH_LONG) {
val snack = Snackbar.make(this, message, length)
snack.show()
}
view.snack("Welcome to GDD")
view.snack("Welcome to GDD", Snackbar.LENGTH_SHORT)
Java
Kotlin
Wow moments
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
class Address {
String name = ...;
String street = ...;
String city = ...;
String state = ...;
String zip = ...;
}
Address address = new Address();
System.out.println(address.getName());
System.out.println(address.getStreet());
class Address {
var name: String = ...
var street: String = ...
var city: String = ...
var state: String? = ...
var zip: String = ...
}
val address = Address()
println(address.name)
println(address.street)
Java Kotlin
Wow moments
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
scrollView.postDelayed(new Runnable() {
@Override
public void run() {
doSomething(position);
}
}, 250);
scrollView.postDelayed({
onTabPageSelected(position) }, 200)
Java Kotlin
Wow moments
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
List<User> users = api.getUsers();
List<User> activeUsers = new
ArrayList<>();
for (User user : users) {
if (user.isActive()) {
activeUsers.add(user);
}
}
adapter.setUsers(activeUsers);
val users = api.getUsers()
val activeUsersNames = items.filter {
it.active
}
adapter.setUsers(activeUsers)
Java Kotlin
Wow moments
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
private class GetWeatherTask extends
AsyncTask<String, Void, Forecast> {
protected Forecast doInBackground(String
zipCode) {
return WeatherAPI().execute(zipCode);
}
protected void onPostExecute(Forecast
result) {
showData(result);
}
}
new GetWeatherTask().execute(380015);
fun loadWeatherData() = async(UI) {
val waiter = bg {
WeatherApi(zipCode).execute() }
showData(waiter.await())
}
Java Kotlin
Wow moments
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
@Override
public boolean onOptionsItemSelected(MenuItem
item) {
switch (item.getItemId()) {
case R.id.new_game:
newGame();
return true;
case R.id.help:
showHelp();
return true;
default:
return
super.onOptionsItemSelected(item);
}
}
override fun onOptionsItemSelected(item:
MenuItem) = when (item.itemId) {
R.id.new_game -> consume {
navigateToNewGame() }
R.id.help -> drawer.consume {
navigateToHelp() }
else -> super.onOptionsItemSelected(item)
}
inline fun consume(f: () -> Unit): Boolean {
f()
return true
}
Java Kotlin
Wow moments
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
if (obj instanceof TextArea) {
((TextArea)obj).append("some data");
} else {
// Do something
}
if (view is TextArea) {
view.append("Kotlin is awesome!")
} else {
// Do something
}
Java Kotlin
Wow moments
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
textView {
id = R.id.errorView
textColor = ContextCompat.getColor(ctx, R.color.red_error)
text = string(R.string.error_view_login_text)
textSize = 14f
visibility = View.GONE
}
textView {
lparams(width = matchParent, height = wrapContent) {
gravity = Gravity.CENTER
leftMargin = dip(16)
rightMargin = dip(16)
}
}
Wow moments
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
// Showing Alerts
alert("Hi, are you enjoying the Kotlin talk?") {
yesButton { toast("Yes :)") }
noButton {}
}.show()
// Showing progress dialog
val dialog = progressDialog(message = "Please wait a bit…", title = "Fetching data")
// Showing SnackBar
snackbar(view, "Hi there!")
snackbar(view, R.string.message)
longSnackbar(view, "Wow, such duration")
snackbar(view, "Action, reaction", "Click me!") { doStuff() }
Wow moments
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
anObservable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.map(new Func1<String, List<String>>() {
@Override
public List<String> call(String s) {
...
}
})
.subscribe(new Observer<List<String>>() {
...
anObservable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread(
))
.map { }
.doOnNext{ }
.subscribe { data -> }
Java Kotlin
Wow moments
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
@Test
public void
testSomethingWorksAsExpected() {
Assert.assertTrue(false);
}
Java
@Test fun `test something works as
expected`() {
Assert.assertTrue(false)
}
Also
import org.mockito.Mockito.`when` as
_when
Kotlin
Wow moments
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
JVM Native
iOS, etc.
JS
Kotlin
Android Spring, etc.
Future of Kotlin
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
References
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
● Kotlin official website
● Android official website
● Git repo from Developer Advocate at JetBrains
● Android Pub
● Antonio Leiva's blog
● Bob’s blog
● Anko Github page
● Sample Android app using Kotlin
References
Email: trivedi.hardik.11@gmail.com Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
Thank You
@MrHardikTrivedi{ }
Source : https://developers.google.com/events/gdd-india/

More Related Content

What's hot (20)

PDF
Kotlin Developer Starter in Android projects
Bartosz Kosarzycki
 
PDF
Kotlin - Better Java
Dariusz Lorenc
 
PDF
Kotlin for Android Development
Speck&Tech
 
PDF
Kotlin hands on - MorningTech ekito 2017
Arnaud Giuliani
 
PDF
Taking Kotlin to production, Seriously
Haim Yadid
 
PDF
Kotlin for Android devs
Adit Lal
 
PPTX
Say Goodbye To Java: Getting Started With Kotlin For Android Development
Adam Magaña
 
PPTX
K is for Kotlin
TechMagic
 
PPTX
Getting Started With Kotlin
Gaurav sharma
 
PDF
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan s.r.o.
 
PDF
Coding for Android on steroids with Kotlin
Kai Koenig
 
PDF
Anko - The Ultimate Ninja of Kotlin Libraries?
Kai Koenig
 
PDF
Summer of Tech 2017 - Kotlin/Android bootcamp
Kai Koenig
 
PDF
Building microservices with Kotlin
Haim Yadid
 
PDF
Develop your next app with kotlin @ AndroidMakersFr 2017
Arnaud Giuliani
 
PDF
Kotlin cheat sheet by ekito
Arnaud Giuliani
 
PPT
The Kotlin Programming Language
intelliyole
 
PDF
Kotlin, smarter development for the jvm
Arnaud Giuliani
 
PDF
Kotlin advanced - language reference for android developers
Bartosz Kosarzycki
 
PPTX
Design patterns with kotlin
Alexey Soshin
 
Kotlin Developer Starter in Android projects
Bartosz Kosarzycki
 
Kotlin - Better Java
Dariusz Lorenc
 
Kotlin for Android Development
Speck&Tech
 
Kotlin hands on - MorningTech ekito 2017
Arnaud Giuliani
 
Taking Kotlin to production, Seriously
Haim Yadid
 
Kotlin for Android devs
Adit Lal
 
Say Goodbye To Java: Getting Started With Kotlin For Android Development
Adam Magaña
 
K is for Kotlin
TechMagic
 
Getting Started With Kotlin
Gaurav sharma
 
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan s.r.o.
 
Coding for Android on steroids with Kotlin
Kai Koenig
 
Anko - The Ultimate Ninja of Kotlin Libraries?
Kai Koenig
 
Summer of Tech 2017 - Kotlin/Android bootcamp
Kai Koenig
 
Building microservices with Kotlin
Haim Yadid
 
Develop your next app with kotlin @ AndroidMakersFr 2017
Arnaud Giuliani
 
Kotlin cheat sheet by ekito
Arnaud Giuliani
 
The Kotlin Programming Language
intelliyole
 
Kotlin, smarter development for the jvm
Arnaud Giuliani
 
Kotlin advanced - language reference for android developers
Bartosz Kosarzycki
 
Design patterns with kotlin
Alexey Soshin
 

Similar to Kotlin a problem solver - gdd extended pune (20)

PDF
CodeWay 2019 - Gandalf: Bad code shall not pass
Ilya Ghirici
 
PPTX
Kotlin / Android Update
Garth Gilmour
 
PPTX
從零開始學 Android
秀吉(Hsiu-Chi) 蔡(Tsai)
 
PPTX
Gerrit Code Review: how to script a plugin with Scala and Groovy
Luca Milanesio
 
PPTX
Sword fighting with Dagger GDG-NYC Jan 2016
Mike Nakhimovich
 
PPTX
GDG Kuwait - Modern android development
GDGKuwaitGoogleDevel
 
PPTX
TypeScript Vs. KotlinJS
Garth Gilmour
 
PPTX
Lies Told By The Kotlin Compiler
Garth Gilmour
 
PDF
Kotlin: Why Do You Care?
intelliyole
 
PDF
Behavioural Driven Development in Zf2
David Contavalli
 
PDF
Jorge Carmona | Kotlin pro-tips | Codemotion Madrid 2018
Codemotion
 
PPTX
NDRIOD PROGRAMMINLesson 2 Functions.pptx
MassaKinG
 
PPTX
Lies Told By The Kotlin Compiler
Garth Gilmour
 
PDF
Little Did He Know ...
Burt Beckwith
 
PDF
#MBLTdev: Разработка первоклассных SDK для Android (Twitter)
e-Legion
 
PPTX
Gradle: One technology to build them all
Bonitasoft
 
PDF
Dark side of Android apps modularization
David Bilík
 
PDF
Koin Quickstart
Matthew Clarke
 
PDF
Enter the gradle
Parameswari Ettiappan
 
PPTX
Boost up your productivity with Kotlin - Liferay Symposium France 2018
Louis-Guillaume Durand
 
CodeWay 2019 - Gandalf: Bad code shall not pass
Ilya Ghirici
 
Kotlin / Android Update
Garth Gilmour
 
從零開始學 Android
秀吉(Hsiu-Chi) 蔡(Tsai)
 
Gerrit Code Review: how to script a plugin with Scala and Groovy
Luca Milanesio
 
Sword fighting with Dagger GDG-NYC Jan 2016
Mike Nakhimovich
 
GDG Kuwait - Modern android development
GDGKuwaitGoogleDevel
 
TypeScript Vs. KotlinJS
Garth Gilmour
 
Lies Told By The Kotlin Compiler
Garth Gilmour
 
Kotlin: Why Do You Care?
intelliyole
 
Behavioural Driven Development in Zf2
David Contavalli
 
Jorge Carmona | Kotlin pro-tips | Codemotion Madrid 2018
Codemotion
 
NDRIOD PROGRAMMINLesson 2 Functions.pptx
MassaKinG
 
Lies Told By The Kotlin Compiler
Garth Gilmour
 
Little Did He Know ...
Burt Beckwith
 
#MBLTdev: Разработка первоклассных SDK для Android (Twitter)
e-Legion
 
Gradle: One technology to build them all
Bonitasoft
 
Dark side of Android apps modularization
David Bilík
 
Koin Quickstart
Matthew Clarke
 
Enter the gradle
Parameswari Ettiappan
 
Boost up your productivity with Kotlin - Liferay Symposium France 2018
Louis-Guillaume Durand
 
Ad

Kotlin a problem solver - gdd extended pune

  • 1. Kotlin for Android A Real Problem Solver Hardik Trivedi Source : https://developers.google.com/events/gdd-india/
  • 2. Hardik Trivedi ● I am a computer program writer ● Works at Globant, Pune, IN ● An active community speaker ● Co-author of a book "Kotlin Blueprints" ● I love writing tech blogs ● I am mentor for college graduates and professionals and consultant to companies About Me Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
  • 3. Exciting talk and training from Sean @ GDDIndia Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com Day 1: Testing Out Kotlin Testing is a great way to learn Kotlin, write readable tests, and introduce your development team to the power of Kotlin. Learn how to use Kotlin through a deep dive into writing tests. Day 2: Taking Advantage of Kotlin in Your Android App Hands-on experience building Android apps using Android Studio in the Kotlin language. Checkout code at https://goo.gl/SyGJ1i Sean McQuillan Android Developer @ Google
  • 4. Why Kotlin? Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com It’s a Modern ● Type Inference ● First class functions ● Abstraction ● Lambdas ● Extensions ● Coroutines
  • 5. Why Kotlin? Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com It’s built for Industry ● Not only expressive but keeps Performance in mind ● Readable ● Easy to write scalable code ● It’s targeting JVM, mobile and browsers ● Great tooling support from JetBrains
  • 6. Why Kotlin? Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com It’s easy to Use ● Interoperability ● Learn in a day ● No surprises
  • 7. Kotlin announcements Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com ● Kotlin 1.2 is out. It has ability to reuse code between JVM and JavaScript ● Kotlin/Native 0.5 is out and it has power calling Kotlin from Swift, C and LLVM 5 ● Added a style guide https://android.github.io/kotlin-guides/style.html It has all the standards Google has used to code in Kotlin ● Added Kotlin/Native support to CLion ● Jetbrains release official Kotlin wrappers to work with React.JS ● Android Lint has support to Kotlin. You can also write custom lint rules for Kotlin.
  • 8. Kotlin Basics.inc(){ } Source : https://developers.google.com/events/gdd-india/
  • 9. Extension Function Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com val str = "GGDD Extendedd" fun String.removeFirstLastChar(): String { return this.substring(1, this.length - 1) } str.removeFirstLastChar()// Output is GDD Extended
  • 10. Extension Function Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com fun View.visible() { this.visibility = View.VISIBLE } fun View.gone() { this.visibility = View.GONE } button.visible() textView.gone()
  • 11. Delegated Properties Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com Properties usually contains the direct corresponding value But Kotlin allows you to delegate some task/behaviour to the properties if managed properly. ● lazy properties: the value gets computed only upon first access; ● observable properties: listeners get notified about changes to this property; ● storing properties in a map, instead of a separate field for each property.
  • 12. Delegated Properties - Vetoable Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com class Veto { var value: String by Delegates.vetoable("String") { prop, old, new -> new.contains("GDD") } } val veto = Veto() veto.value = "DevFest" println(veto.value) // Output String veto.value="GDD Extended Pune" println(veto.value) // Output GDD Extended Pune
  • 13. Semantic Validation Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com Many times we do parameter validation thorough and aggressively static String join(String sep, List<String> strings) { if (sep == null) throw new NullPointerException("sep == null"); if (sep.length() < 2) { throw new IllegalArgumentException("sep.length() < 2"); } if (strings == null) throw new NullPointerException("strings == null"); ... }
  • 14. Semantic Validation Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com ● With Guava like libraries you can avoid those null checks and manage the pre conditions gracefully. ● But you don’t add guava for to use only one feature. ● Kotlin avoids nullability by default and it has functions for semantic validations. fun join(sep: String, strings: List<String>): String { require(sep.length < 2) { "sep.length() < 2" } ... }
  • 15. Let function Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com Java String data=null; if(data!=null) { // Do something } Kotlin var data: String? = null data?.let { // it == data always not null and read only once }
  • 16. Let function Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com class Concurrent { @Volatile var data: String? = null fun doSomething() { data?.let { //data always not null and read only once } } }
  • 17. Higher-order function Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com A higher-order function is a function that takes functions as parameters, or returns a function. fun logExecution(func: () -> Unit) { Log.d("tag", "before executing func") func() Log.d("tag", "after executing func") } logExecution({ yourFunction() })
  • 18. Wow moments See Kotlin in Action !!!{ } Source : https://developers.google.com/events/gdd-india/
  • 19. Wow moments Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com // Possible only if it's Java 8 public interface InterfaceA { default void defaultMethod(){ System.out.println("Interface A default method"); } } interface ToolbarManager { fun initToolbar() { toolbar.inflateMenu(R.menu.main_menu) toolbar.setOnMenuItemClickListener { // Your code true } } } Java Kotlin
  • 20. Wow moments Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com Button clickButton = (Button) findViewById(R.id.clickButton); clickButton.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { ***Do what you want with the click here*** } }); import kotlinx.android.synthetic.main.activity_ detail.* clickButton.setOnClickListener { ***Do what you want with the click here*** } Java Kotlin
  • 21. Wow moments Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com private String readInputStream(InputStream is) throws Exception { String line = null; StringBuilder sb = new StringBuilder(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is)); while ((line = bufferedReader.readLine()) != null) { sb.append(line); } bufferedReader.close(); return sb.toString(); } val inputAsString = is.bufferedReader().use { it.readText() } // defaults to UTF-8 Java Kotlin
  • 22. Wow moments public class MySingleton { private static MySingleton myObj; private MySingleton(){ } public static MySingleton getInstance(){ if(myObj == null){ myObj = new MySingleton(); } return myObj; } } object MySingleton { var num: Int = 0 fun domeSomeThing() { println("Kotlin is awesome!!!") } } Java Kotlin Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
  • 23. Wow moments Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com SharedPreferences sharedpreferences = getSharedPreferences(mypreference, Context.MODE_PRIVATE); email.setText(sharedpreferences.getStrin g(Email, "")); SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putString("email", "[email protected]"); editor.apply(); private var email: String by DelegatedPreference(this, "email", "") email="[email protected]" txtEmail.text=email Java Kotlin
  • 24. Wow moments Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com Movie movie = moviesList.get(position); holder.title.setText(movie.getTitle()); holder.genre.setText(movie.getGenre()); holder.year.setText(movie.getYear()); Movie movie = moviesList[position] with(movie) { holder.title.text=title holder.genre.text=genre holder.year.text=year } Java Kotlin
  • 25. Wow moments Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com private class GetWeatherTask extends AsyncTask<String, Void, Forecast> { protected Forecast doInBackground(String zipCode) { return WeatherAPI().execute(zipCode); } protected void onPostExecute(Forecast result) { showData(result); } } new GetWeatherTask().execute(380015); fun loadWeatherData() = async(UI) { val waiter = bg { WeatherApi(zipCode).execute() } showData(waiter.await()) } Java Kotlin
  • 26. Wow moments Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com Intent intent = Intent(this,SomeOtherActivity.class) intent.putExtra("id", 5) intent.setFlag(Intent.FLAG_ACTIVITY_SINGLE_TOP) startActivity(intent) startActivity(intentFor<SomeOtherActivity>("id" to 5).singleTop()) Java Kotlin
  • 27. Wow moments Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_update_info, container, false); } fun ViewGroup.inflate(@LayoutRes layoutRes: Int, attachToRoot: Boolean = false): View { return LayoutInflater.from(context).inflate(layoutRes, this, attachToRoot) } parent.inflate(R.layout.my_layout) parent.inflate(R.layout.my_layout, true) Java Kotlin
  • 28. Wow moments Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com Picasso.with(context).load(R.mipmap.ic_launcher).into(imageView); fun ImageView.loadUrl(url: String) { Picasso.with(context).load(url).into(this) } imageView.loadUrl("http://....") Java Kotlin
  • 29. Wow moments Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com getSupportFragmentManager().beginTransaction() .add(R.id.container,DataFragment.newInstance(), "detail") .addToBackStack() .commit(); fun AppCompatActivity.addFragment(fragment: Fragment, frameId: Int, backStackTag: String? = null) { supportFragmentManager.inTransaction { add(frameId, fragment) backStackTag?.let { addToBackStack(fragment.javaClass.name) } } } addFragment(DataFragment.newInstance(), R.id.container, "detail") Java Kotlin
  • 30. Snackbar snackbar = Snackbar .make(coordinatorLayout, "Welcome to GDD", Snackbar.LENGTH_LONG); snackbar.show(); inline fun View.snack(message: String, length: Int = Snackbar.LENGTH_LONG) { val snack = Snackbar.make(this, message, length) snack.show() } view.snack("Welcome to GDD") view.snack("Welcome to GDD", Snackbar.LENGTH_SHORT) Java Kotlin Wow moments Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
  • 31. class Address { String name = ...; String street = ...; String city = ...; String state = ...; String zip = ...; } Address address = new Address(); System.out.println(address.getName()); System.out.println(address.getStreet()); class Address { var name: String = ... var street: String = ... var city: String = ... var state: String? = ... var zip: String = ... } val address = Address() println(address.name) println(address.street) Java Kotlin Wow moments Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
  • 32. scrollView.postDelayed(new Runnable() { @Override public void run() { doSomething(position); } }, 250); scrollView.postDelayed({ onTabPageSelected(position) }, 200) Java Kotlin Wow moments Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
  • 33. Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com List<User> users = api.getUsers(); List<User> activeUsers = new ArrayList<>(); for (User user : users) { if (user.isActive()) { activeUsers.add(user); } } adapter.setUsers(activeUsers); val users = api.getUsers() val activeUsersNames = items.filter { it.active } adapter.setUsers(activeUsers) Java Kotlin Wow moments Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
  • 34. Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com private class GetWeatherTask extends AsyncTask<String, Void, Forecast> { protected Forecast doInBackground(String zipCode) { return WeatherAPI().execute(zipCode); } protected void onPostExecute(Forecast result) { showData(result); } } new GetWeatherTask().execute(380015); fun loadWeatherData() = async(UI) { val waiter = bg { WeatherApi(zipCode).execute() } showData(waiter.await()) } Java Kotlin Wow moments Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
  • 35. @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.new_game: newGame(); return true; case R.id.help: showHelp(); return true; default: return super.onOptionsItemSelected(item); } } override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { R.id.new_game -> consume { navigateToNewGame() } R.id.help -> drawer.consume { navigateToHelp() } else -> super.onOptionsItemSelected(item) } inline fun consume(f: () -> Unit): Boolean { f() return true } Java Kotlin Wow moments Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
  • 36. if (obj instanceof TextArea) { ((TextArea)obj).append("some data"); } else { // Do something } if (view is TextArea) { view.append("Kotlin is awesome!") } else { // Do something } Java Kotlin Wow moments Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
  • 37. Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com textView { id = R.id.errorView textColor = ContextCompat.getColor(ctx, R.color.red_error) text = string(R.string.error_view_login_text) textSize = 14f visibility = View.GONE } textView { lparams(width = matchParent, height = wrapContent) { gravity = Gravity.CENTER leftMargin = dip(16) rightMargin = dip(16) } } Wow moments Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
  • 38. Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com // Showing Alerts alert("Hi, are you enjoying the Kotlin talk?") { yesButton { toast("Yes :)") } noButton {} }.show() // Showing progress dialog val dialog = progressDialog(message = "Please wait a bit…", title = "Fetching data") // Showing SnackBar snackbar(view, "Hi there!") snackbar(view, R.string.message) longSnackbar(view, "Wow, such duration") snackbar(view, "Action, reaction", "Click me!") { doStuff() } Wow moments Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
  • 39. anObservable .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .map(new Func1<String, List<String>>() { @Override public List<String> call(String s) { ... } }) .subscribe(new Observer<List<String>>() { ... anObservable .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread( )) .map { } .doOnNext{ } .subscribe { data -> } Java Kotlin Wow moments Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
  • 40. @Test public void testSomethingWorksAsExpected() { Assert.assertTrue(false); } Java @Test fun `test something works as expected`() { Assert.assertTrue(false) } Also import org.mockito.Mockito.`when` as _when Kotlin Wow moments Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
  • 41. Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com JVM Native iOS, etc. JS Kotlin Android Spring, etc. Future of Kotlin Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
  • 42. References Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com ● Kotlin official website ● Android official website ● Git repo from Developer Advocate at JetBrains ● Android Pub ● Antonio Leiva's blog ● Bob’s blog ● Anko Github page ● Sample Android app using Kotlin References Email: [email protected] Follow: @MrHardikTrivedi Visit: trivedihardik.wordpress.com
  • 43. Thank You @MrHardikTrivedi{ } Source : https://developers.google.com/events/gdd-india/