SlideShare uma empresa Scribd logo
1 de 29
Baixar para ler offline
Kotlin lang - basics
(Android projects)
Bartosz Kosarzycki - StxNext Lightning Talks - Feb 12, 2016
talented developers | flexible teams | agile experts
KOTLINhttp://kotlinlang.org/
Required knowledge:
● basic Android development skills
● functional programming
● familiarity with JDK 6,7,8
● Scala is a plus
What is it?
KOTLIN is:
● safe
● versatile
● interoparable
● IDE support
● fast
JAVA SCALA
KOTLIN
+ fast compilation
+ simplicity
+ swift’s syntax is similar
Online compiler:
http://try.kotlinlang.org/
SWIFT
Why KOTLIN?
● no javax.time from JDK8
● no try-with resources
● no lambdas!
● no new java stream api
● no way to add methods to
platform data types (e.g. View)
List<string> names = students.stream()
.map(Student::getName)
.filter(name->name.startsWith("B"))
.collect(Collectors.toList());
ZoneId zone = ZoneId.systemDefault();
Clock clock = Clock.system(zone);
LocalDate date = LocalDate.now();
LocalTime time = LocalTime.now();
time = time.plus(Period.ofDays(12));
javax.time
Java Stream API
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br =
new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
try-with resources
Advantages
fun finish(obj: Any) {
if (obj is Activity)
obj.finish()
}
Auto-casting:
Named args in func calls:
fun circle(x: Int, y: Int, rad: Int, stroke: Int) {…}
circle(15, 40, rad = 20, stroke = 1);
Built-in lambdas:
val numbers: IntArray = intArrayOf(11, 20, 31, 40, 51)
val predicate: (Int) -> Boolean = { it -> it % 2 == 1 }
val list1 = numbers.filter { it % 2 == 1 }
val list2 = numbers.filter(predicate)
println("Lists identical: " + list1.equals(list2));
> Lists identical: true
Compactness:
* no new statement:
val a = B();
* optional brackets, return statement and one-line
function declarations:
class A {
var field1: String = "No ";
fun printNews () = field1 + " news for you" ;
}
println(A().printNews())
● all of these are much-needed
in Android development
Nullpointer
safety
var output : String?
output = null
println(output!!.length)
Exception in thread "main" kotlin.KotlinNullPointerException
at Simplest_versionKt.main(Simplest version.kt:11)
Java-like !! Operator: (for NPE lovers) - Optional.get() equivalent
var output : String?
output = null
println(output?.length)
val len = output?.length ?: -1 //elvis operator
println(len)
> null
> -1
?. Safe calls: (for if not null -> call function; return null otherwise)
Kotlin type aliases - planned in roadmap
(not yet released - as of Feb 2016)
Java JDK 10 will push Optional onto
the default stack ~ 2018
Optional<> pattern no longer
needed!
kotlin.Unit
If a function does not return any useful value, its
return type is Unit
Advantages
val arr = arrayOf(D("1A", "1B"),
D( "2A", "2B"), D("3A", "3B"));
for ((first, second) in arr )
println("a: $first, b: $second")
class D {
public var nameA: String = ""
public var nameB: String = ""
constructor (nameA: String , nameB: String) {
this.nameA = nameA
this.nameB = nameB
}
operator fun component1() : String {
return nameA
}
operator fun component2() : String {
return nameB
}
}
(a, b) Destructuring Declaration
Singleton:
object SampleSingleton {
var baseUrl: String = "https://aaa.bbb"
fun printUrl() = println(baseUrl)
}
SampleSingleton.printUrl()
SampleSingleton.baseUrl = "https://ccc.ddd"
SampleSingleton.printUrl()
> https://aaa.bbb
> https://ccc.ddd
● Singletons and
destructuring declarations
are built-in:
Data objects
data class Point(val x: Double = 0.0, val y: Double = 0.0, var descr: String?)
val point1 = Point( x = 1.0, y = 2.0, descr = "no description");
val point2 = Point( descr = "no description", y = 2.0, x = 1.0);
println(point1.equals(point2))
println(point1.hashCode().equals(point2.hashCode()) )
println(point1.toString().equals(point2.toString()) )
println(point1.toString())
Data object:
hashCode()
toString()
equals()
+ properties
Automatically generated:● removes most of
the boilerplate
code
Traits
TRAITS - java-like interfaces
with default implementation
class ExampleActivity :
AppCompatActivity(), ActivitySessionHandling {
override fun onDestroy() {
super.onDestroy()
closeSession()
}
}
open interface ActivitySessionHandling {
fun closeSession() = println("Session closed")
}
JAVA JDK 8 - extension methods
- default interface implementation
public class ItemListActivity extends AppCompatActivity
implements Java8DefaultInterface {
@Override
protected void onDestroy() {
super.onDestroy();
closeSession();
}
}
public interface Java8DefaultInterface {
default void closeSession() {
Log.i("TAG", "Session closed");
}
}
(not available in Android)
Class
delegation
Built-in delegate pattern:
class Derived(b: Base) : Base by b
class BaseImpl(val x: Int) : Base {
override fun print() { println(x) }
}
interface Base {
fun print()
}
val b = BaseImpl(10)
Derived(b).print()
> 10
Java equivalent:
class Derived {
Base base;
public Derived(Base b) {
this.base = b;
}
void print(){
base.print();
}
}
class BaseImpl implements Base {
int val;
public BaseImpl(int v) {
this.val = v;
}
public void print() { System.out.println(val); }
}
interface Base {
void print();
}
BaseImpl base = new BaseImpl(10);
new Derived(base).print();
Properties
Properties & read-only properties:
public class Address(addr : String) {
public var name: String = ""
public val address: String = addr //read-only
}
val address = Address(addr = "Low street 123")
address.name = "Mickey mouse"
println(address.address)
println(address.name)
> Low street 123
> Mickey mouse
address.address = "Another street 123" //Error:
val cannot be reassigned
Getters & setters:
public class Address() {
var address: String
get() = "Lorem ipsum"
set(value) {
println(value)
}
}
public class Address() {
var address: String = ""
get //default getter
private set //default private setter
}
Companion objects:
class CarAssemblyFactory {
companion object Factory {
fun createCar(): String
= String().plus("This is a car")
}
}
println(CarAssemblyFactory.createCar())
Utility
classes
UTILS:
StringUtil
ActivityUtil
ListUtil
JAVA utility class
public class StringUtils {
public static String encodeString(String str) {
return str.replaceAll(" ", "_");
}
}
KOTLIN utility class
fun String.encodeSpaces():String = this.replace(" ", "_")
println("Neque porro quisquam".encodeSpaces())
Separate packages:
package main.kotlin.utils
fun String.encodeSpaces(): String = this.replace(" ", "_")
import main.kotlin.utils.encodeSpaces
println("Neque porro quisquam".encodeSpaces())
● no utils hell
● extend final classes
● classes in Kotlin are
final by default
@JvmName("DateUtil")
fun Date.isTuesday() = day == 2
//in fact it's:
//Date.getDay() == 2
+ KOTLIN
Project
structure
Android kotlin project structure: Kotlin & Java intertwined:
Gradle dependencies:
build.gradle:
buildscript {
dependencies {
classpath 'com.android.tools.build:gradle:2.0.0-beta3'
classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.0.0-rc-1036'
}
}
app.gradle:
apply plugin: 'kotlin-android'
Cost
Reference application:
one blank Activity app generated with Android Studio
Higher-order
functions
Introduction
//extension function
fun Date.isTuesday() = day == 2
//function expression as contant
val addition = { x: Int, y:Int -> x + y }
//higher order function
fun higherOrder(x : Int, y: Int, func : (x : Int, y : Int) -> Int ) : Int { return func.invoke(x, y); }
Higher-order extension function
fun Int.addCustomFunc(arg: Int, func : (x : Int, y : Int) -> Int ) : Int
{ return func.invoke(this, arg); }
val addition = { x: Int, y:Int -> x + y }
val result = 1.addCustomFunc(5, addition);
Android
Compactness
mDescriptionTextView.setOnClickListener({ activityPrivateMethod() })
mDescriptionTextView.setOnClickListener({
mDescriptionTextView.text = "Current time: " + DateTime.now() })
Lambda expression to the rescue
private fun bind(item: Team) {
mHeaderTextView.text = item.header
mDescriptionTextView.text = item.description
}
mSampleEditText.addTextChangedListener{
onTextChanged { text:CharSequence, a:Int, b:Int, c:Int ->
Toast.makeText(applicationContext, text, LENGTH_SHORT).show() } }
● simplify development
● remove boilerplate
● improve multi-threading
Auto getters&setters
Helpers ● Lambda expressions in EditText listeners
● usually handled by kotlin android libs
class TextWatcherFunctions : TextWatcher {
private var _beforeTextChanged : ((CharSequence , Int, Int, Int) -> Unit)? = null
private var _onTextChanged : ((CharSequence , Int, Int, Int) -> Unit)? = null
private var _afterTextChanged : ((Editable) -> Unit)? = null
override fun beforeTextChanged
(s: CharSequence , start: Int , count: Int , after: Int) : Unit
= _beforeTextChanged ?.invoke(s , start, count, after) ?: Unit ;
override fun onTextChanged
(s: CharSequence , start: Int , before: Int , count: Int) : Unit
= _onTextChanged ?.invoke(s , start, before, count) ?: Unit
override fun afterTextChanged (s: Editable) : Unit
= _afterTextChanged ?.invoke(s) ?: Unit
fun beforeTextChanged (function: (CharSequence , Int, Int, Int) -> Unit) {
_beforeTextChanged = function
}
fun onTextChanged (function: (CharSequence , Int, Int, Int) -> Unit) {
_onTextChanged = function
}
fun afterTextChanged (function: (Editable) -> Unit) {
_afterTextChanged = function
}
}
fun EditText.addTextChangedListener
(init: TextWatcherFunctions.()
-> Unit): TextWatcher {
val watcher = TextWatcherFunctions()
watcher.init()
addTextChangedListener(watcher)
return watcher
}
Kotterknife
val mHeaderTextView: TextView by bindView(R.id.activity_team_details_team_header)
val mDescriptionTextView: TextView by bindView(R.id.activity_team_details_team_description)
val textViews: List<TextView> by bindViews(R.id.activity_team_details_team_header,
R.id.activity_team_details_team_description)
// List binding with optional items being omitted.
val nameViews: List<TextView> by bindOptionalViews(R.id.first_name, R.id.middle_name, R.id.last_name)
● bindView() instead of
@Bind annotation
● developed by Jake Wharton
● still not pushed to maven
central
Dagger 2
& KOTLIN
@Module
class AndroidModule(private val application: Application) {
@Provides
@Singleton
fun provideLocationManager(): LocationManager {
return
application
.getSystemService(Context.LOCATION_SERVICE)
as LocationManager
}
@Provides
@Singleton
@Named("something")
fun provideSomething(): String {
return "something"
}
}
class MainActivity : AppCompatActivity() {
@Inject
lateinit var locationManager: LocationManager
@field:[Inject Named("something")]
lateinit var something: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
● compatible with KOTLIN
since M13
● introduction of lateinit property
Late-initialized property: e.g. for unit tests
public class MyTest {
lateinit var subject: TestSubject
@SetUp fun setup() {
subject = TestSubject()
}
@Test fun test() {
subject.method()
}
}
Kotlin Anko
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
verticalLayout {
padding = dip(30)
editText {
hint = "Name"
textSize = 24f
}
editText {
hint = "Password"
textSize = 24f
}
button("Login") {
textSize = 26f
}
}
}
● from Jetbrains
● create layouts from code
dependencies {
compile 'org.jetbrains.anko:anko-sdk15:0.8'
compile 'org.jetbrains.anko:anko-support-v4:0.8'
compile 'org.jetbrains.anko:anko-appcompat-v7:0.8'
}
verticalLayout {
val name = editText()
button("Say Hello") {
onClick { toast("Hello, ${name.text}!") }
}
}
Sample
Activity
class TeamDetailsActivity : AppCompatActivity() {
val mHeaderTextView: TextView by bindView(R.id.activity_team_details_team_header)
var mTeam: Team? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_team_details)
supportActionBar!!.title = "Team description"
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
mTeam = Gson().fromJson<Team>(intent.getStringExtra("item"), Team::class.java)
bind(mTeam!!)
}
private fun bind(item: Team) {
mHeaderTextView.text = item.header
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home)
finish()
return super.onOptionsItemSelected(item)
}
}
● 100% Java compatibility
● kotterknife
● Android SDK usage in Kotlin is simple
SWIFT
var myVariable = 42 //Variable
val explicitDouble: Double = 70.0 //Explicit Type Constant
for (i in 1..5) { print(i) } //Inclusive Range Operator
val a = "A"; val b = "B";
val str = "I have ${a + b} "; //String interpolation
var shoppingList = arrayOf("catfish" , "water") //Array Creation
var hashMap = hashMapOf("Malcolm" to "Captain" ); //Maps
val emptyArray = arrayOf<String>() //Empty Typed Array
interface Nameable { fun name(): String } //Interface
val movie = obj as Movie //Downcasting
fun Double.km() : Double = this * 1000; //Extension function
KOTLIN SWIFT
var myVariable = 42 //Variable
let explicitDouble: Double = 70 //Explicit Type Constant
for i in 1...5 { println( i) } //Inclusive Range Operator
let a = "A"; let b = "B";
let str = "I have (a + b) " //String interpolation
var shoppingList = [ "catfish" , "water"] //Array Creation
var occupations = [ "Malcolm" : "Captain" ] //Maps
let emptyArray = String[]() //Empty Typed Array
protocol Nameable { func name() -> String } //Protocol (Interface)
let movie = object as Movie //Downcasting
extension Double { var km: Double { return self * 1_000.0 } }
//Extension function
● Kotlin’s syntax is similar
Swift
Command line
compiler
$ curl -s get.sdkman.io | bash
$ source "$HOME/.sdkman/bin/sdkman-init.sh"
$ sdk install kotlin
Do you want kotlin 1.0.0-rc-1036 to be set as default?
(Y/n): Y
Setting kotlin 1.0.0-rc-1036 as default.
Installation:
● Let us compare the
resulting bytecode of
kotlin and java
compilation
OsX
SDKMAN
or homebrew
Linux
FreeBSD
Cygwin
SDKMAN
Command line
compiler
Kotlin:
class Capturing {
fun run2(func: Runnable) {
func.run()
}
}
fun main(args: Array<String>) {
Capturing().run2(Runnable { println("Hey! $args") })
}
$ kotlinc Capturing.kt
$ javap -p
Compiled from "Capturing.kt"
public final class Capturing {
public final void run2(java.lang.Runnable);
public Capturing();
}
public final class CapturingKt {
public static final void main(java.lang.String[]);
}
Java:
● Let us compare the
resulting bytecode of
kotlin and java
compilation
import java.util.Arrays;
class Capturing {
public static void main(final String... args) {
run(new Runnable() {
@Override public void run() {
System.out.println("Hey! " + Arrays.toString(args));
}
});
}
private static void run(Runnable run) {
run.run();
}
}
$ javac Capturing.java
$ javap -p Capturing
Compiled from "Capturing.java"
class Capturing {
Capturing();
public static void main(java.lang.String...);
private static void run(java.lang.Runnable);
}
What is
KOTLIN :)?
RUSSIAN WARSHIP
ISLAND
source:
https://en.wikipedia.org/wiki/Kotlin
CITY IN POLAND
KETCHUP BRANDPROGRAMMING
LANGUAGE
Comparison
KOTLIN
WORSE THAN SCALA: BETTER THAN SCALA:
● no static members (BY DESIGN) - if you need something that
is not attached to an instance of any class, you define it in a
package
● no checked exceptions (BY DESIGN)
no functions like:
void copy(CharSequence csq) throws IOException
● primitive types that are not classes
● non-private fields (i.e. java’s public int field; ) - by design - in kotlin
one should use properties instead of public fields
IN JAVA NOT IN KOTLIN:
● Overridable type members
● Path-dependent types
● Macros
● Existential types
● Complicated logic for initialization of traits
● Custom symbolic operations
● Built-in XML
● Parallel collections
● Structural types
● Value types
● Yield operator
● Actors
● smart-casts
● first-class delegation (built-in delegate pattern)
● no overhead in extension functions
(compared to implicit class in Scala [link])
● no overhead in null-safety
Resources
RESOURCES:
● http://kotlinlang.org/
● Jake Wharton - Using Project Kotlin for Android - https://t.co/9t8qsBGPlo
● Mike Gouline - Kotlin the Swift of Android - - https://blog.gouline.net/2014/08/31/kotlin-the-swift-of-android/
● Paweł Gajda - Kotlin Android - http://slides.com/pawegio/kotlin-android, https://github.com/pawegio/KAndroid
● Jetbrains Kotlin Anko - https://github.com/Kotlin/anko
● Amit Phaltankar Java 8 streams - https://dzone.com/articles/understanding-java-8-streams-1
● Salomon Brys - https://github.com/SalomonBrys
● Gautier Mechling - http://nilhcem.github.io/swift-is-like-kotlin/
Thankyou!
Bartosz Kosarzycki
bartosz.kosarzycki@stxnext.pl
Twitter: @bkosarzycki
Online compiler:
http://try.kotlinlang.org/

Mais conteúdo relacionado

Mais procurados

Kotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyKotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyMobileAcademy
 
Kotlin cheat sheet by ekito
Kotlin cheat sheet by ekitoKotlin cheat sheet by ekito
Kotlin cheat sheet by ekitoArnaud Giuliani
 
Kotlin boost yourproductivity
Kotlin boost yourproductivityKotlin boost yourproductivity
Kotlin boost yourproductivitynklmish
 
Taking Kotlin to production, Seriously
Taking Kotlin to production, SeriouslyTaking Kotlin to production, Seriously
Taking Kotlin to production, SeriouslyHaim Yadid
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoMuhammad Abdullah
 
The Kotlin Programming Language, Svetlana Isakova
The Kotlin Programming Language, Svetlana IsakovaThe Kotlin Programming Language, Svetlana Isakova
The Kotlin Programming Language, Svetlana IsakovaVasil Remeniuk
 
Swift and Kotlin Presentation
Swift and Kotlin PresentationSwift and Kotlin Presentation
Swift and Kotlin PresentationAndrzej Sitek
 
Coding for Android on steroids with Kotlin
Coding for Android on steroids with KotlinCoding for Android on steroids with Kotlin
Coding for Android on steroids with KotlinKai Koenig
 
Little Helpers for Android Development with Kotlin
Little Helpers for Android Development with KotlinLittle Helpers for Android Development with Kotlin
Little Helpers for Android Development with KotlinKai Koenig
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Languageintelliyole
 
Java Keeps Throttling Up!
Java Keeps Throttling Up!Java Keeps Throttling Up!
Java Keeps Throttling Up!José Paumard
 
Intro to Kotlin
Intro to KotlinIntro to Kotlin
Intro to KotlinMagda Miu
 
Kotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime PerformanceKotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime Performanceintelliyole
 
2017: Kotlin - now more than ever
2017: Kotlin - now more than ever2017: Kotlin - now more than ever
2017: Kotlin - now more than everKai Koenig
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?Tomasz Wrobel
 
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...eMan s.r.o.
 
Kotlin as a Better Java
Kotlin as a Better JavaKotlin as a Better Java
Kotlin as a Better JavaGarth Gilmour
 

Mais procurados (19)

Kotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyKotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRready
 
Kotlin
KotlinKotlin
Kotlin
 
Kotlin cheat sheet by ekito
Kotlin cheat sheet by ekitoKotlin cheat sheet by ekito
Kotlin cheat sheet by ekito
 
Kotlin boost yourproductivity
Kotlin boost yourproductivityKotlin boost yourproductivity
Kotlin boost yourproductivity
 
Taking Kotlin to production, Seriously
Taking Kotlin to production, SeriouslyTaking Kotlin to production, Seriously
Taking Kotlin to production, Seriously
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demo
 
The Kotlin Programming Language, Svetlana Isakova
The Kotlin Programming Language, Svetlana IsakovaThe Kotlin Programming Language, Svetlana Isakova
The Kotlin Programming Language, Svetlana Isakova
 
Swift and Kotlin Presentation
Swift and Kotlin PresentationSwift and Kotlin Presentation
Swift and Kotlin Presentation
 
Coding for Android on steroids with Kotlin
Coding for Android on steroids with KotlinCoding for Android on steroids with Kotlin
Coding for Android on steroids with Kotlin
 
Little Helpers for Android Development with Kotlin
Little Helpers for Android Development with KotlinLittle Helpers for Android Development with Kotlin
Little Helpers for Android Development with Kotlin
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Language
 
Java Keeps Throttling Up!
Java Keeps Throttling Up!Java Keeps Throttling Up!
Java Keeps Throttling Up!
 
Intro to Kotlin
Intro to KotlinIntro to Kotlin
Intro to Kotlin
 
Kotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime PerformanceKotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime Performance
 
2017: Kotlin - now more than ever
2017: Kotlin - now more than ever2017: Kotlin - now more than ever
2017: Kotlin - now more than ever
 
Kotlin - Better Java
Kotlin - Better JavaKotlin - Better Java
Kotlin - Better Java
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
 
Kotlin as a Better Java
Kotlin as a Better JavaKotlin as a Better Java
Kotlin as a Better Java
 

Semelhante a Kotlin Developer Starter in Android projects

Kotlin / Android Update
Kotlin / Android UpdateKotlin / Android Update
Kotlin / Android UpdateGarth Gilmour
 
Java patterns in Scala
Java patterns in ScalaJava patterns in Scala
Java patterns in ScalaRadim Pavlicek
 
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingGarth Gilmour
 
Dart, unicorns and rainbows
Dart, unicorns and rainbowsDart, unicorns and rainbows
Dart, unicorns and rainbowschrisbuckett
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for KotlinTechMagic
 
Roslyn: el futuro de C# y VB.NET by Rodolfo Finochietti
Roslyn: el futuro de C# y VB.NET by Rodolfo FinochiettiRoslyn: el futuro de C# y VB.NET by Rodolfo Finochietti
Roslyn: el futuro de C# y VB.NET by Rodolfo Finochietti.NET Conf UY
 
Jug trojmiasto 2014.04.24 tricky stuff in java grammar and javac
Jug trojmiasto 2014.04.24  tricky stuff in java grammar and javacJug trojmiasto 2014.04.24  tricky stuff in java grammar and javac
Jug trojmiasto 2014.04.24 tricky stuff in java grammar and javacAnna Brzezińska
 
Dart structured web apps
Dart   structured web appsDart   structured web apps
Dart structured web appschrisbuckett
 
The Future of JVM Languages
The Future of JVM Languages The Future of JVM Languages
The Future of JVM Languages VictorSzoltysek
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghStuart Roebuck
 
Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and MonoidsHugo Gävert
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()daewon jeong
 
Things about Functional JavaScript
Things about Functional JavaScriptThings about Functional JavaScript
Things about Functional JavaScriptChengHui Weng
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
Lies Told By The Kotlin Compiler
Lies Told By The Kotlin CompilerLies Told By The Kotlin Compiler
Lies Told By The Kotlin CompilerGarth Gilmour
 

Semelhante a Kotlin Developer Starter in Android projects (20)

Kotlin / Android Update
Kotlin / Android UpdateKotlin / Android Update
Kotlin / Android Update
 
Java patterns in Scala
Java patterns in ScalaJava patterns in Scala
Java patterns in Scala
 
TechTalk - Dotnet
TechTalk - DotnetTechTalk - Dotnet
TechTalk - Dotnet
 
SCALA - Functional domain
SCALA -  Functional domainSCALA -  Functional domain
SCALA - Functional domain
 
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
 
Dart, unicorns and rainbows
Dart, unicorns and rainbowsDart, unicorns and rainbows
Dart, unicorns and rainbows
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for Kotlin
 
Roslyn: el futuro de C# y VB.NET by Rodolfo Finochietti
Roslyn: el futuro de C# y VB.NET by Rodolfo FinochiettiRoslyn: el futuro de C# y VB.NET by Rodolfo Finochietti
Roslyn: el futuro de C# y VB.NET by Rodolfo Finochietti
 
Roslyn: el futuro de C#
Roslyn: el futuro de C#Roslyn: el futuro de C#
Roslyn: el futuro de C#
 
Jug trojmiasto 2014.04.24 tricky stuff in java grammar and javac
Jug trojmiasto 2014.04.24  tricky stuff in java grammar and javacJug trojmiasto 2014.04.24  tricky stuff in java grammar and javac
Jug trojmiasto 2014.04.24 tricky stuff in java grammar and javac
 
Dart structured web apps
Dart   structured web appsDart   structured web apps
Dart structured web apps
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
The Future of JVM Languages
The Future of JVM Languages The Future of JVM Languages
The Future of JVM Languages
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and Monoids
 
ASP.NET
ASP.NETASP.NET
ASP.NET
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
 
Things about Functional JavaScript
Things about Functional JavaScriptThings about Functional JavaScript
Things about Functional JavaScript
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Lies Told By The Kotlin Compiler
Lies Told By The Kotlin CompilerLies Told By The Kotlin Compiler
Lies Told By The Kotlin Compiler
 

Mais de Bartosz Kosarzycki

Droidcon Online 2020 quick summary
Droidcon Online 2020 quick summaryDroidcon Online 2020 quick summary
Droidcon Online 2020 quick summaryBartosz Kosarzycki
 
Flutter overview - advantages & disadvantages for business
Flutter overview - advantages & disadvantages for businessFlutter overview - advantages & disadvantages for business
Flutter overview - advantages & disadvantages for businessBartosz Kosarzycki
 
Flutter CI & Device Farms for Flutter
Flutter CI & Device Farms for FlutterFlutter CI & Device Farms for Flutter
Flutter CI & Device Farms for FlutterBartosz Kosarzycki
 
Drone racing - beginner's guide
Drone racing - beginner's guideDrone racing - beginner's guide
Drone racing - beginner's guideBartosz Kosarzycki
 
Optimize apps for Chromebooks - Meet.Intive Oct, 2018
Optimize apps for Chromebooks - Meet.Intive Oct, 2018Optimize apps for Chromebooks - Meet.Intive Oct, 2018
Optimize apps for Chromebooks - Meet.Intive Oct, 2018Bartosz Kosarzycki
 
Android - Gradle build optimisation 3d83f31339d239abcc55f869e5f30348?s=47
Android - Gradle build optimisation  3d83f31339d239abcc55f869e5f30348?s=47Android - Gradle build optimisation  3d83f31339d239abcc55f869e5f30348?s=47
Android - Gradle build optimisation 3d83f31339d239abcc55f869e5f30348?s=47Bartosz Kosarzycki
 
Android things introduction - Development for IoT
Android things introduction - Development for IoTAndroid things introduction - Development for IoT
Android things introduction - Development for IoTBartosz Kosarzycki
 
Daggerate your code - Write your own annotation processor
Daggerate your code - Write your own annotation processorDaggerate your code - Write your own annotation processor
Daggerate your code - Write your own annotation processorBartosz Kosarzycki
 
Introduction to Flutter - truly crossplatform, amazingly fast
Introduction to Flutter - truly crossplatform, amazingly fastIntroduction to Flutter - truly crossplatform, amazingly fast
Introduction to Flutter - truly crossplatform, amazingly fastBartosz Kosarzycki
 
Git-flow workflow and pull-requests
Git-flow workflow and pull-requestsGit-flow workflow and pull-requests
Git-flow workflow and pull-requestsBartosz Kosarzycki
 

Mais de Bartosz Kosarzycki (15)

Droidcon Summary 2021
Droidcon Summary 2021Droidcon Summary 2021
Droidcon Summary 2021
 
Droidcon Online 2020 quick summary
Droidcon Online 2020 quick summaryDroidcon Online 2020 quick summary
Droidcon Online 2020 quick summary
 
Provider vs BLoC vs Redux
Provider vs BLoC vs ReduxProvider vs BLoC vs Redux
Provider vs BLoC vs Redux
 
Animations in Flutter
Animations in FlutterAnimations in Flutter
Animations in Flutter
 
Flutter overview - advantages & disadvantages for business
Flutter overview - advantages & disadvantages for businessFlutter overview - advantages & disadvantages for business
Flutter overview - advantages & disadvantages for business
 
Flutter CI & Device Farms for Flutter
Flutter CI & Device Farms for FlutterFlutter CI & Device Farms for Flutter
Flutter CI & Device Farms for Flutter
 
Drone racing - beginner's guide
Drone racing - beginner's guideDrone racing - beginner's guide
Drone racing - beginner's guide
 
Optimize apps for Chromebooks - Meet.Intive Oct, 2018
Optimize apps for Chromebooks - Meet.Intive Oct, 2018Optimize apps for Chromebooks - Meet.Intive Oct, 2018
Optimize apps for Chromebooks - Meet.Intive Oct, 2018
 
Android - Gradle build optimisation 3d83f31339d239abcc55f869e5f30348?s=47
Android - Gradle build optimisation  3d83f31339d239abcc55f869e5f30348?s=47Android - Gradle build optimisation  3d83f31339d239abcc55f869e5f30348?s=47
Android - Gradle build optimisation 3d83f31339d239abcc55f869e5f30348?s=47
 
DroidCon Berlin 2018 summary
DroidCon Berlin 2018 summaryDroidCon Berlin 2018 summary
DroidCon Berlin 2018 summary
 
Android things introduction - Development for IoT
Android things introduction - Development for IoTAndroid things introduction - Development for IoT
Android things introduction - Development for IoT
 
Daggerate your code - Write your own annotation processor
Daggerate your code - Write your own annotation processorDaggerate your code - Write your own annotation processor
Daggerate your code - Write your own annotation processor
 
Android antipatterns
Android antipatternsAndroid antipatterns
Android antipatterns
 
Introduction to Flutter - truly crossplatform, amazingly fast
Introduction to Flutter - truly crossplatform, amazingly fastIntroduction to Flutter - truly crossplatform, amazingly fast
Introduction to Flutter - truly crossplatform, amazingly fast
 
Git-flow workflow and pull-requests
Git-flow workflow and pull-requestsGit-flow workflow and pull-requests
Git-flow workflow and pull-requests
 

Último

TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...apidays
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 

Último (20)

TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 

Kotlin Developer Starter in Android projects

  • 1. Kotlin lang - basics (Android projects) Bartosz Kosarzycki - StxNext Lightning Talks - Feb 12, 2016 talented developers | flexible teams | agile experts
  • 2. KOTLINhttp://kotlinlang.org/ Required knowledge: ● basic Android development skills ● functional programming ● familiarity with JDK 6,7,8 ● Scala is a plus
  • 3. What is it? KOTLIN is: ● safe ● versatile ● interoparable ● IDE support ● fast JAVA SCALA KOTLIN + fast compilation + simplicity + swift’s syntax is similar Online compiler: http://try.kotlinlang.org/ SWIFT
  • 4. Why KOTLIN? ● no javax.time from JDK8 ● no try-with resources ● no lambdas! ● no new java stream api ● no way to add methods to platform data types (e.g. View) List<string> names = students.stream() .map(Student::getName) .filter(name->name.startsWith("B")) .collect(Collectors.toList()); ZoneId zone = ZoneId.systemDefault(); Clock clock = Clock.system(zone); LocalDate date = LocalDate.now(); LocalTime time = LocalTime.now(); time = time.plus(Period.ofDays(12)); javax.time Java Stream API static String readFirstLineFromFile(String path) throws IOException { try (BufferedReader br = new BufferedReader(new FileReader(path))) { return br.readLine(); } } try-with resources
  • 5. Advantages fun finish(obj: Any) { if (obj is Activity) obj.finish() } Auto-casting: Named args in func calls: fun circle(x: Int, y: Int, rad: Int, stroke: Int) {…} circle(15, 40, rad = 20, stroke = 1); Built-in lambdas: val numbers: IntArray = intArrayOf(11, 20, 31, 40, 51) val predicate: (Int) -> Boolean = { it -> it % 2 == 1 } val list1 = numbers.filter { it % 2 == 1 } val list2 = numbers.filter(predicate) println("Lists identical: " + list1.equals(list2)); > Lists identical: true Compactness: * no new statement: val a = B(); * optional brackets, return statement and one-line function declarations: class A { var field1: String = "No "; fun printNews () = field1 + " news for you" ; } println(A().printNews()) ● all of these are much-needed in Android development
  • 6. Nullpointer safety var output : String? output = null println(output!!.length) Exception in thread "main" kotlin.KotlinNullPointerException at Simplest_versionKt.main(Simplest version.kt:11) Java-like !! Operator: (for NPE lovers) - Optional.get() equivalent var output : String? output = null println(output?.length) val len = output?.length ?: -1 //elvis operator println(len) > null > -1 ?. Safe calls: (for if not null -> call function; return null otherwise) Kotlin type aliases - planned in roadmap (not yet released - as of Feb 2016) Java JDK 10 will push Optional onto the default stack ~ 2018 Optional<> pattern no longer needed! kotlin.Unit If a function does not return any useful value, its return type is Unit
  • 7. Advantages val arr = arrayOf(D("1A", "1B"), D( "2A", "2B"), D("3A", "3B")); for ((first, second) in arr ) println("a: $first, b: $second") class D { public var nameA: String = "" public var nameB: String = "" constructor (nameA: String , nameB: String) { this.nameA = nameA this.nameB = nameB } operator fun component1() : String { return nameA } operator fun component2() : String { return nameB } } (a, b) Destructuring Declaration Singleton: object SampleSingleton { var baseUrl: String = "https://aaa.bbb" fun printUrl() = println(baseUrl) } SampleSingleton.printUrl() SampleSingleton.baseUrl = "https://ccc.ddd" SampleSingleton.printUrl() > https://aaa.bbb > https://ccc.ddd ● Singletons and destructuring declarations are built-in:
  • 8. Data objects data class Point(val x: Double = 0.0, val y: Double = 0.0, var descr: String?) val point1 = Point( x = 1.0, y = 2.0, descr = "no description"); val point2 = Point( descr = "no description", y = 2.0, x = 1.0); println(point1.equals(point2)) println(point1.hashCode().equals(point2.hashCode()) ) println(point1.toString().equals(point2.toString()) ) println(point1.toString()) Data object: hashCode() toString() equals() + properties Automatically generated:● removes most of the boilerplate code
  • 9. Traits TRAITS - java-like interfaces with default implementation class ExampleActivity : AppCompatActivity(), ActivitySessionHandling { override fun onDestroy() { super.onDestroy() closeSession() } } open interface ActivitySessionHandling { fun closeSession() = println("Session closed") } JAVA JDK 8 - extension methods - default interface implementation public class ItemListActivity extends AppCompatActivity implements Java8DefaultInterface { @Override protected void onDestroy() { super.onDestroy(); closeSession(); } } public interface Java8DefaultInterface { default void closeSession() { Log.i("TAG", "Session closed"); } } (not available in Android)
  • 10. Class delegation Built-in delegate pattern: class Derived(b: Base) : Base by b class BaseImpl(val x: Int) : Base { override fun print() { println(x) } } interface Base { fun print() } val b = BaseImpl(10) Derived(b).print() > 10 Java equivalent: class Derived { Base base; public Derived(Base b) { this.base = b; } void print(){ base.print(); } } class BaseImpl implements Base { int val; public BaseImpl(int v) { this.val = v; } public void print() { System.out.println(val); } } interface Base { void print(); } BaseImpl base = new BaseImpl(10); new Derived(base).print();
  • 11. Properties Properties & read-only properties: public class Address(addr : String) { public var name: String = "" public val address: String = addr //read-only } val address = Address(addr = "Low street 123") address.name = "Mickey mouse" println(address.address) println(address.name) > Low street 123 > Mickey mouse address.address = "Another street 123" //Error: val cannot be reassigned Getters & setters: public class Address() { var address: String get() = "Lorem ipsum" set(value) { println(value) } } public class Address() { var address: String = "" get //default getter private set //default private setter } Companion objects: class CarAssemblyFactory { companion object Factory { fun createCar(): String = String().plus("This is a car") } } println(CarAssemblyFactory.createCar())
  • 12. Utility classes UTILS: StringUtil ActivityUtil ListUtil JAVA utility class public class StringUtils { public static String encodeString(String str) { return str.replaceAll(" ", "_"); } } KOTLIN utility class fun String.encodeSpaces():String = this.replace(" ", "_") println("Neque porro quisquam".encodeSpaces()) Separate packages: package main.kotlin.utils fun String.encodeSpaces(): String = this.replace(" ", "_") import main.kotlin.utils.encodeSpaces println("Neque porro quisquam".encodeSpaces()) ● no utils hell ● extend final classes ● classes in Kotlin are final by default @JvmName("DateUtil") fun Date.isTuesday() = day == 2 //in fact it's: //Date.getDay() == 2
  • 14. Project structure Android kotlin project structure: Kotlin & Java intertwined: Gradle dependencies: build.gradle: buildscript { dependencies { classpath 'com.android.tools.build:gradle:2.0.0-beta3' classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.0.0-rc-1036' } } app.gradle: apply plugin: 'kotlin-android'
  • 15. Cost Reference application: one blank Activity app generated with Android Studio
  • 16. Higher-order functions Introduction //extension function fun Date.isTuesday() = day == 2 //function expression as contant val addition = { x: Int, y:Int -> x + y } //higher order function fun higherOrder(x : Int, y: Int, func : (x : Int, y : Int) -> Int ) : Int { return func.invoke(x, y); } Higher-order extension function fun Int.addCustomFunc(arg: Int, func : (x : Int, y : Int) -> Int ) : Int { return func.invoke(this, arg); } val addition = { x: Int, y:Int -> x + y } val result = 1.addCustomFunc(5, addition);
  • 17. Android Compactness mDescriptionTextView.setOnClickListener({ activityPrivateMethod() }) mDescriptionTextView.setOnClickListener({ mDescriptionTextView.text = "Current time: " + DateTime.now() }) Lambda expression to the rescue private fun bind(item: Team) { mHeaderTextView.text = item.header mDescriptionTextView.text = item.description } mSampleEditText.addTextChangedListener{ onTextChanged { text:CharSequence, a:Int, b:Int, c:Int -> Toast.makeText(applicationContext, text, LENGTH_SHORT).show() } } ● simplify development ● remove boilerplate ● improve multi-threading Auto getters&setters
  • 18. Helpers ● Lambda expressions in EditText listeners ● usually handled by kotlin android libs class TextWatcherFunctions : TextWatcher { private var _beforeTextChanged : ((CharSequence , Int, Int, Int) -> Unit)? = null private var _onTextChanged : ((CharSequence , Int, Int, Int) -> Unit)? = null private var _afterTextChanged : ((Editable) -> Unit)? = null override fun beforeTextChanged (s: CharSequence , start: Int , count: Int , after: Int) : Unit = _beforeTextChanged ?.invoke(s , start, count, after) ?: Unit ; override fun onTextChanged (s: CharSequence , start: Int , before: Int , count: Int) : Unit = _onTextChanged ?.invoke(s , start, before, count) ?: Unit override fun afterTextChanged (s: Editable) : Unit = _afterTextChanged ?.invoke(s) ?: Unit fun beforeTextChanged (function: (CharSequence , Int, Int, Int) -> Unit) { _beforeTextChanged = function } fun onTextChanged (function: (CharSequence , Int, Int, Int) -> Unit) { _onTextChanged = function } fun afterTextChanged (function: (Editable) -> Unit) { _afterTextChanged = function } } fun EditText.addTextChangedListener (init: TextWatcherFunctions.() -> Unit): TextWatcher { val watcher = TextWatcherFunctions() watcher.init() addTextChangedListener(watcher) return watcher }
  • 19. Kotterknife val mHeaderTextView: TextView by bindView(R.id.activity_team_details_team_header) val mDescriptionTextView: TextView by bindView(R.id.activity_team_details_team_description) val textViews: List<TextView> by bindViews(R.id.activity_team_details_team_header, R.id.activity_team_details_team_description) // List binding with optional items being omitted. val nameViews: List<TextView> by bindOptionalViews(R.id.first_name, R.id.middle_name, R.id.last_name) ● bindView() instead of @Bind annotation ● developed by Jake Wharton ● still not pushed to maven central
  • 20. Dagger 2 & KOTLIN @Module class AndroidModule(private val application: Application) { @Provides @Singleton fun provideLocationManager(): LocationManager { return application .getSystemService(Context.LOCATION_SERVICE) as LocationManager } @Provides @Singleton @Named("something") fun provideSomething(): String { return "something" } } class MainActivity : AppCompatActivity() { @Inject lateinit var locationManager: LocationManager @field:[Inject Named("something")] lateinit var something: String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } } ● compatible with KOTLIN since M13 ● introduction of lateinit property Late-initialized property: e.g. for unit tests public class MyTest { lateinit var subject: TestSubject @SetUp fun setup() { subject = TestSubject() } @Test fun test() { subject.method() } }
  • 21. Kotlin Anko override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) verticalLayout { padding = dip(30) editText { hint = "Name" textSize = 24f } editText { hint = "Password" textSize = 24f } button("Login") { textSize = 26f } } } ● from Jetbrains ● create layouts from code dependencies { compile 'org.jetbrains.anko:anko-sdk15:0.8' compile 'org.jetbrains.anko:anko-support-v4:0.8' compile 'org.jetbrains.anko:anko-appcompat-v7:0.8' } verticalLayout { val name = editText() button("Say Hello") { onClick { toast("Hello, ${name.text}!") } } }
  • 22. Sample Activity class TeamDetailsActivity : AppCompatActivity() { val mHeaderTextView: TextView by bindView(R.id.activity_team_details_team_header) var mTeam: Team? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_team_details) supportActionBar!!.title = "Team description" supportActionBar!!.setDisplayHomeAsUpEnabled(true) mTeam = Gson().fromJson<Team>(intent.getStringExtra("item"), Team::class.java) bind(mTeam!!) } private fun bind(item: Team) { mHeaderTextView.text = item.header } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) finish() return super.onOptionsItemSelected(item) } } ● 100% Java compatibility ● kotterknife ● Android SDK usage in Kotlin is simple
  • 23. SWIFT var myVariable = 42 //Variable val explicitDouble: Double = 70.0 //Explicit Type Constant for (i in 1..5) { print(i) } //Inclusive Range Operator val a = "A"; val b = "B"; val str = "I have ${a + b} "; //String interpolation var shoppingList = arrayOf("catfish" , "water") //Array Creation var hashMap = hashMapOf("Malcolm" to "Captain" ); //Maps val emptyArray = arrayOf<String>() //Empty Typed Array interface Nameable { fun name(): String } //Interface val movie = obj as Movie //Downcasting fun Double.km() : Double = this * 1000; //Extension function KOTLIN SWIFT var myVariable = 42 //Variable let explicitDouble: Double = 70 //Explicit Type Constant for i in 1...5 { println( i) } //Inclusive Range Operator let a = "A"; let b = "B"; let str = "I have (a + b) " //String interpolation var shoppingList = [ "catfish" , "water"] //Array Creation var occupations = [ "Malcolm" : "Captain" ] //Maps let emptyArray = String[]() //Empty Typed Array protocol Nameable { func name() -> String } //Protocol (Interface) let movie = object as Movie //Downcasting extension Double { var km: Double { return self * 1_000.0 } } //Extension function ● Kotlin’s syntax is similar Swift
  • 24. Command line compiler $ curl -s get.sdkman.io | bash $ source "$HOME/.sdkman/bin/sdkman-init.sh" $ sdk install kotlin Do you want kotlin 1.0.0-rc-1036 to be set as default? (Y/n): Y Setting kotlin 1.0.0-rc-1036 as default. Installation: ● Let us compare the resulting bytecode of kotlin and java compilation OsX SDKMAN or homebrew Linux FreeBSD Cygwin SDKMAN
  • 25. Command line compiler Kotlin: class Capturing { fun run2(func: Runnable) { func.run() } } fun main(args: Array<String>) { Capturing().run2(Runnable { println("Hey! $args") }) } $ kotlinc Capturing.kt $ javap -p Compiled from "Capturing.kt" public final class Capturing { public final void run2(java.lang.Runnable); public Capturing(); } public final class CapturingKt { public static final void main(java.lang.String[]); } Java: ● Let us compare the resulting bytecode of kotlin and java compilation import java.util.Arrays; class Capturing { public static void main(final String... args) { run(new Runnable() { @Override public void run() { System.out.println("Hey! " + Arrays.toString(args)); } }); } private static void run(Runnable run) { run.run(); } } $ javac Capturing.java $ javap -p Capturing Compiled from "Capturing.java" class Capturing { Capturing(); public static void main(java.lang.String...); private static void run(java.lang.Runnable); }
  • 26. What is KOTLIN :)? RUSSIAN WARSHIP ISLAND source: https://en.wikipedia.org/wiki/Kotlin CITY IN POLAND KETCHUP BRANDPROGRAMMING LANGUAGE
  • 27. Comparison KOTLIN WORSE THAN SCALA: BETTER THAN SCALA: ● no static members (BY DESIGN) - if you need something that is not attached to an instance of any class, you define it in a package ● no checked exceptions (BY DESIGN) no functions like: void copy(CharSequence csq) throws IOException ● primitive types that are not classes ● non-private fields (i.e. java’s public int field; ) - by design - in kotlin one should use properties instead of public fields IN JAVA NOT IN KOTLIN: ● Overridable type members ● Path-dependent types ● Macros ● Existential types ● Complicated logic for initialization of traits ● Custom symbolic operations ● Built-in XML ● Parallel collections ● Structural types ● Value types ● Yield operator ● Actors ● smart-casts ● first-class delegation (built-in delegate pattern) ● no overhead in extension functions (compared to implicit class in Scala [link]) ● no overhead in null-safety
  • 28. Resources RESOURCES: ● http://kotlinlang.org/ ● Jake Wharton - Using Project Kotlin for Android - https://t.co/9t8qsBGPlo ● Mike Gouline - Kotlin the Swift of Android - - https://blog.gouline.net/2014/08/31/kotlin-the-swift-of-android/ ● Paweł Gajda - Kotlin Android - http://slides.com/pawegio/kotlin-android, https://github.com/pawegio/KAndroid ● Jetbrains Kotlin Anko - https://github.com/Kotlin/anko ● Amit Phaltankar Java 8 streams - https://dzone.com/articles/understanding-java-8-streams-1 ● Salomon Brys - https://github.com/SalomonBrys ● Gautier Mechling - http://nilhcem.github.io/swift-is-like-kotlin/