SlideShare a Scribd company logo
1 of 29
Download to read 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/

More Related Content

What's hot

Kotlin cheat sheet by ekito
Kotlin cheat sheet by ekitoKotlin cheat sheet by ekito
Kotlin cheat sheet by ekitoArnaud Giuliani
 
Kotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyKotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyMobileAcademy
 
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017Hardik Trivedi
 
scala.reflect, Eugene Burmako
scala.reflect, Eugene Burmakoscala.reflect, Eugene Burmako
scala.reflect, Eugene BurmakoVasil Remeniuk
 
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
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoMuhammad Abdullah
 
Taking Kotlin to production, Seriously
Taking Kotlin to production, SeriouslyTaking Kotlin to production, Seriously
Taking Kotlin to production, SeriouslyHaim Yadid
 
Java Keeps Throttling Up!
Java Keeps Throttling Up!Java Keeps Throttling Up!
Java Keeps Throttling Up!José Paumard
 
Swift and Kotlin Presentation
Swift and Kotlin PresentationSwift and Kotlin Presentation
Swift and Kotlin PresentationAndrzej Sitek
 
Kotlin boost yourproductivity
Kotlin boost yourproductivityKotlin boost yourproductivity
Kotlin boost yourproductivitynklmish
 
Kotlin 101 for Java Developers
Kotlin 101 for Java DevelopersKotlin 101 for Java Developers
Kotlin 101 for Java DevelopersChristoph Pickl
 
Kotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime PerformanceKotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime Performanceintelliyole
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for KotlinTechMagic
 
Intro to Kotlin
Intro to KotlinIntro to Kotlin
Intro to KotlinMagda Miu
 
Building native Android applications with Mirah and Pindah
Building native Android applications with Mirah and PindahBuilding native Android applications with Mirah and Pindah
Building native Android applications with Mirah and PindahNick Plante
 

What's hot (20)

Kotlin cheat sheet by ekito
Kotlin cheat sheet by ekitoKotlin cheat sheet by ekito
Kotlin cheat sheet by ekito
 
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
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
 
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
 
scala.reflect, Eugene Burmako
scala.reflect, Eugene Burmakoscala.reflect, Eugene Burmako
scala.reflect, Eugene Burmako
 
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
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demo
 
Taking Kotlin to production, Seriously
Taking Kotlin to production, SeriouslyTaking Kotlin to production, Seriously
Taking Kotlin to production, Seriously
 
Java Keeps Throttling Up!
Java Keeps Throttling Up!Java Keeps Throttling Up!
Java Keeps Throttling Up!
 
Swift and Kotlin Presentation
Swift and Kotlin PresentationSwift and Kotlin Presentation
Swift and Kotlin Presentation
 
Kotlin boost yourproductivity
Kotlin boost yourproductivityKotlin boost yourproductivity
Kotlin boost yourproductivity
 
Kotlin 101 for Java Developers
Kotlin 101 for Java DevelopersKotlin 101 for Java Developers
Kotlin 101 for Java Developers
 
Kotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime PerformanceKotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime Performance
 
Kotlin - Better Java
Kotlin - Better JavaKotlin - Better Java
Kotlin - Better Java
 
Android antipatterns
Android antipatternsAndroid antipatterns
Android antipatterns
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for Kotlin
 
Javantura v2 - All Together Now - making Groovy and Scala sing together - Din...
Javantura v2 - All Together Now - making Groovy and Scala sing together - Din...Javantura v2 - All Together Now - making Groovy and Scala sing together - Din...
Javantura v2 - All Together Now - making Groovy and Scala sing together - Din...
 
Intro to Kotlin
Intro to KotlinIntro to Kotlin
Intro to Kotlin
 
Building native Android applications with Mirah and Pindah
Building native Android applications with Mirah and PindahBuilding native Android applications with Mirah and Pindah
Building native Android applications with Mirah and Pindah
 

Similar to Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016

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
 
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
 
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17LogeekNightUkraine
 

Similar to Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016 (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
 
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
 
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
 

More from STX Next

Scrum Master - Breakout session.
Scrum Master - Breakout session.Scrum Master - Breakout session.
Scrum Master - Breakout session.STX Next
 
Transformation to agile.
Transformation to agile.Transformation to agile.
Transformation to agile.STX Next
 
What scrum masters and product owners should know about software quality and ...
What scrum masters and product owners should know about software quality and ...What scrum masters and product owners should know about software quality and ...
What scrum masters and product owners should know about software quality and ...STX Next
 
The essence hidden from the eye.
The essence hidden from the eye. The essence hidden from the eye.
The essence hidden from the eye. STX Next
 
Why to nearshore in Central Europe?
Why to nearshore in Central Europe?Why to nearshore in Central Europe?
Why to nearshore in Central Europe?STX Next
 
Is there a common pattern in fixing projects?
Is there a common pattern in fixing projects?Is there a common pattern in fixing projects?
Is there a common pattern in fixing projects?STX Next
 
Behave automatically: (Almost) Effortless feature testing
Behave automatically: (Almost) Effortless feature testingBehave automatically: (Almost) Effortless feature testing
Behave automatically: (Almost) Effortless feature testingSTX Next
 
Time to React!
Time to React!Time to React!
Time to React!STX Next
 
Salary Formula - bumpy road to transparency.
Salary Formula - bumpy road to transparency.Salary Formula - bumpy road to transparency.
Salary Formula - bumpy road to transparency.STX Next
 
Software Quality Visualization
Software Quality Visualization Software Quality Visualization
Software Quality Visualization STX Next
 
Kotlin Advanced - language reference for Android developers
Kotlin Advanced - language reference for Android developers Kotlin Advanced - language reference for Android developers
Kotlin Advanced - language reference for Android developers STX Next
 
Discover, Define, Deliver - a workflow to create successful digital products.
Discover, Define, Deliver - a workflow to create successful digital products. Discover, Define, Deliver - a workflow to create successful digital products.
Discover, Define, Deliver - a workflow to create successful digital products. STX Next
 
Zwinność procesu rekrutacyjnego w branży IT
Zwinność procesu rekrutacyjnego w branży ITZwinność procesu rekrutacyjnego w branży IT
Zwinność procesu rekrutacyjnego w branży ITSTX Next
 
STX Next - Scrum Development Process Overview
STX Next - Scrum Development Process OverviewSTX Next - Scrum Development Process Overview
STX Next - Scrum Development Process OverviewSTX Next
 
STX Next - Meet Us
STX Next - Meet UsSTX Next - Meet Us
STX Next - Meet UsSTX Next
 
Group Process by Example - a PO’s and SM’s perspective
Group Process by Example - a PO’s and SM’s perspectiveGroup Process by Example - a PO’s and SM’s perspective
Group Process by Example - a PO’s and SM’s perspectiveSTX Next
 

More from STX Next (16)

Scrum Master - Breakout session.
Scrum Master - Breakout session.Scrum Master - Breakout session.
Scrum Master - Breakout session.
 
Transformation to agile.
Transformation to agile.Transformation to agile.
Transformation to agile.
 
What scrum masters and product owners should know about software quality and ...
What scrum masters and product owners should know about software quality and ...What scrum masters and product owners should know about software quality and ...
What scrum masters and product owners should know about software quality and ...
 
The essence hidden from the eye.
The essence hidden from the eye. The essence hidden from the eye.
The essence hidden from the eye.
 
Why to nearshore in Central Europe?
Why to nearshore in Central Europe?Why to nearshore in Central Europe?
Why to nearshore in Central Europe?
 
Is there a common pattern in fixing projects?
Is there a common pattern in fixing projects?Is there a common pattern in fixing projects?
Is there a common pattern in fixing projects?
 
Behave automatically: (Almost) Effortless feature testing
Behave automatically: (Almost) Effortless feature testingBehave automatically: (Almost) Effortless feature testing
Behave automatically: (Almost) Effortless feature testing
 
Time to React!
Time to React!Time to React!
Time to React!
 
Salary Formula - bumpy road to transparency.
Salary Formula - bumpy road to transparency.Salary Formula - bumpy road to transparency.
Salary Formula - bumpy road to transparency.
 
Software Quality Visualization
Software Quality Visualization Software Quality Visualization
Software Quality Visualization
 
Kotlin Advanced - language reference for Android developers
Kotlin Advanced - language reference for Android developers Kotlin Advanced - language reference for Android developers
Kotlin Advanced - language reference for Android developers
 
Discover, Define, Deliver - a workflow to create successful digital products.
Discover, Define, Deliver - a workflow to create successful digital products. Discover, Define, Deliver - a workflow to create successful digital products.
Discover, Define, Deliver - a workflow to create successful digital products.
 
Zwinność procesu rekrutacyjnego w branży IT
Zwinność procesu rekrutacyjnego w branży ITZwinność procesu rekrutacyjnego w branży IT
Zwinność procesu rekrutacyjnego w branży IT
 
STX Next - Scrum Development Process Overview
STX Next - Scrum Development Process OverviewSTX Next - Scrum Development Process Overview
STX Next - Scrum Development Process Overview
 
STX Next - Meet Us
STX Next - Meet UsSTX Next - Meet Us
STX Next - Meet Us
 
Group Process by Example - a PO’s and SM’s perspective
Group Process by Example - a PO’s and SM’s perspectiveGroup Process by Example - a PO’s and SM’s perspective
Group Process by Example - a PO’s and SM’s perspective
 

Recently uploaded

UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHC Sai Kiran
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substationstephanwindworld
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptSAURABHKUMAR892774
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
computer application and construction management
computer application and construction managementcomputer application and construction management
computer application and construction managementMariconPadriquez1
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 

Recently uploaded (20)

UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECH
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substation
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.ppt
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
computer application and construction management
computer application and construction managementcomputer application and construction management
computer application and construction management
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 

Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016

  • 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/