Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Kotlin Tutorial for Java Developers
Educative profile imageRyan Thelin
Ryan Thelin forEducative

Posted on • Originally published ateducative.io

     

Kotlin Tutorial for Java Developers

Kotlin is a rising programming language that aims to address the flaws of Java and be more seamlessly tied with the adaptable needs of the modern world. While once a niche language, Kotlin is quickly growing and has many companies switching from Java to Kotlin.

In fact, Google announced in 2017 that it wouldofficially support Kotlin, rather than Java, as the main language for Android development.

Now, more and more companies are looking for Kotlin developers. Today, we'll help you transition to this new language by highlighting the differences and syntax of each fundamental Kotlin concept.

Here’s what we’ll cover today:

Transition to Kotlin in half the time

Get right to what you need without wasting time on programming fundamentals you already know.

Kotlin Crash Course for Programmers

Kotlin vs Java

Kotlin is an open-source, statically typed programming language developed by Jetbrains, which is famous for creating the IntelliJ IDEA IDE. The goal of Kotlin is to be an easier-to-use, more concise language for any type of project.

Kotlin is mainly used for Android app development or front-end development with frameworks likeReact.

Kotlin is unique because it is completely interoperable with Java code, meaning you can use existing Java libraries or frameworks. Kotlin code can transpile to JavaScript or Java bytecode for use on the Java Virtual Machine (JVM) orAndroid development.

Modern companies are particularly interested in Kotlin’s versatility because developers can use the same language for any project the company needs.

Asagile development becomes more prevalent, companies likeGoogle,Amazon, Netflix,Uber have started hiring Kotlin developers. In fact, it was ranked4th fastest growing language in 2020 in Github's yearly report, with and many more reporting implementations of Kotlin developers.

Static Typing:

Like Java, variables can only be assigned values that match their type. This allows you to easily catch errors found by the compiler before execution.

varm:Int=12m=10// okm="twelve"// error!m=10.0// error!
Enter fullscreen modeExit fullscreen mode

Non-local jumps:

Kotlin allows you to exit a function anywhere.

funmain(){intArrayOf(4,5,6).forEachlambda@{if(it==5)return@lambdaprintln(it)}println()loop@for(iin0..3){for(jin0..3){if(i+j==4)continue@loopif(i+j==5)break@loopprintln(i+j)}}}
Enter fullscreen modeExit fullscreen mode

Collection filtering:

Allows you to search collections for any data that matches the passed criteria.

vallanguageArray=arrayOf("Serbian","Swahili","Japanese","German","Spanish")valselectedLang=languageArray.filter{name->name.startsWith("s",ignoreCase=true)}//or: .filter { it.startsWith("s", ignoreCase = true) }.sortedBy{name->name.length}.first()
Enter fullscreen modeExit fullscreen mode

Extension functions:

Extension functions allow you to extend existing components without writing methods inside them, leading to cleaner code.

classPerson{varfirstName=...varlastName=...}// Maybe the author of the Person class forgot to include thisfunPerson.setName(firstName:String,lastName:String){this.firstName=firstNamethis.lastName=lastName}
Enter fullscreen modeExit fullscreen mode

Higher-order functions:

Kotlin functions are treated as first-class, meaning they can be passed or returned from other functions.

people.filter{person->person.headCount==1}
Enter fullscreen modeExit fullscreen mode

Lazy loading:

Decreases loading time by only loading resources it'll immediately need.

Key Differences between Kotlin and Java

Kotlin

  • Allows cross-platform transpiling from Kotlin to Android, JVM, and more.

  • Built from the ground up for both functional programming and object-oriented programming.

  • Designed for conciseness.

  • Built-in smart casting and implicit casting.

  • Cannot assignnull values to ensure null safety

  • Out-of-the-box support for modern features like coroutines, extension functions, and data classes.

Java:

  • Not cross-platform, cannot transpile.

  • Built forobject oriented programming with extremely limited functional support.

  • Designed for specificity.

  • Strict explicit typing rules.

  • Allows nulls but throwsnullPointerException, which must be caught with exception handling.

  • Limited support for modern features through complex workarounds.

Keep the learning going.

Transition to Kotlin in half the time with lessons tailored to your current developer skills. Educative's hands-on courses let you learn the tools you need to advance your career without starting back from square one.

Kotlin Crash Course for Programmers

Hello World with Kotlin

Let's take a look at aHello World program in both Java and Kotlin to see the differences.

You can write Kotlin in any Java IDE using the Kotlin plugin or even directly on the command line.

//javaclassHelloWorld{publicstaticvoidmain(String[]args){System.out.println("Hello, World!");}}
Enter fullscreen modeExit fullscreen mode
//kotlinfunmain(){println("Hello, World!")}
Enter fullscreen modeExit fullscreen mode

Clearly, Kotlin is more concise, only using two lines of code. This is because Kotlin allows functions to exist outside of classes, meaning we don't have to declare aHelloWorld class.

  • Online 1 of the Kotlin code, we define themain method. Like Java, every program needs amain function. Kotlin version 1.3+ removed inputs and outputs frommain to make a simpler and less visually cluttered syntax.

  • Online 2, we print the stringHello, World! using the built-inprintln() function. This works the same way as Java's print function but does not need to be pulled from an externalSystem class.

  • At the end ofline 2, notice there is no semicolon to mark the line's end. Kotlin detects the end of statements by line and does not require semicolons.

Kotlin Variables and Data Types

You can define Kotlin variables using either thevar orval keywords.

var<variableName>=<value>//mutableval<variableName>=<value>//read-onlyval<variableName>:<dataType>=<value>//explicittypecasting
Enter fullscreen modeExit fullscreen mode

Variables in Kotlin are very similar to variables in Java except:

  • Kotlin offers immutable (read-only) data types for functional programming

  • Kotlin allows for smart typing, sometimes called implicit typing, where it automatically detects the data type of a variable without explicit tagging.

  • Kotlin does not allow you to assign anull value to variables or return values by default. With Java, you can assignnull, but it will throw anullPointerException if you try to access that value.

Let's see how these differences look in practice.

Read-only vs Mutable Variables:

Variables in Kotlin can be eitherread-only ormutable. The value of read-only variables cannot be changed after they've been initially assigned. Read-only variables are especially helpful in reducing side effects when using functional programming.

Mutable variables are like most variables in Java and can be changed after they've been initialized.

Read-only initialization:

valnumber=17println("number = $number")number=42// Not allowed, throws an exception
Enter fullscreen modeExit fullscreen mode

Mutable initialization:

varnumber=17println("number = $number")number=42// var can be reassignedprintln("number = $number")
Enter fullscreen modeExit fullscreen mode

It's best practice to use read-onlyval variables whenever possible and only use mutablevar when you specifically need it. This minimizes the overall complexity of your programs and makes it easier to understand their data flow.

Kotlin Data Types

Unlike Java, Kotlin does not have primitive data types. All the following types are objects at runtime but do transpile to the respective Java primitive types in Java bytecode.

Integer Types

Kotlin includes all standard integer types. Below examples of explicitly cast, read-only integers that are initialized to their greatest possible values.

valbyte:Byte=127valshort:Short=32767valint:Int=2147483647vallong:Long=9223372036854775807
Enter fullscreen modeExit fullscreen mode

Floating-Point Numbers

Kotlin supports standard decimal and exponent notations.Float andDouble behave the same, butDouble can hold more numbers thanFloat. Kotlin smart casts any floating-point number toDouble, meaning you have to includef at the end of the argument to set a variable as aFloat.

valfloat:Float=3.4028235e38fvaldouble:Double=1.7976931348623157e308
Enter fullscreen modeExit fullscreen mode

Text Types

Kotlin supports Java-likeChar andString types to represent text. You denote single characters with single quotes,'c', and Strings with double quotes"this string".

valcharacter:Char='#'valtext:String="Learning about Kotlin's data types"
Enter fullscreen modeExit fullscreen mode

Unlike Java, Kotlin allows you to easily make multi-line strings using three sets of double quotes,"""<multipleLines>""". Java only offersconcat andline.separator for multi-line strings, which are less concise and require special implementations.

Boolean Type

Kotlin's Boolean type is identical to Java's in function.

valyes:Boolean=truevalno:Boolean=false
Enter fullscreen modeExit fullscreen mode

You can use theas keyword for type conversion of one type to another.

Type inference

Type inference is a compiler feature that allows you to omit types in your code when the compiler can infer it for you. This is also sometimes called smart typing or implicit typing.

If a variable could be declared as two types of differing sizes, it will choose the default:Double for floating-point numbers andInt for integers.

To implicitly declare non-default types, you can add the type key at the end of the value, likeL for typeLong below:

valstring="Educative"valint=27vallong=42Lvaldouble=2.71828valfloat=1.23fvalbool=true
Enter fullscreen modeExit fullscreen mode

Kotlin's type inference system is very robust and allows implicit typing of literals, objects, and complex structures, likelambda expressions.

Kotlin Conditionals and Loops

Kotlin includes two conditional statements,if andwhen, and two loops,for andwhile.

All conditionals are defined using:

<conditional>(<desiredCondition>)<code><conditional>(<desiredCondition>){<codeBlock>}
Enter fullscreen modeExit fullscreen mode

If statement

Kotlinif statement is just like Java's in that it contains a code block which executes if the listed condition becomes true. You can also add anelse statement that executes if theif statement is skipped.

varmax=aif(a<b)max=b// With elsevarmax:Intif(a>b){max=a}else{max=b}// As expressionvalmax=if(a>b)aelseb
Enter fullscreen modeExit fullscreen mode

When Statement

Kotlin also has awhen statement that works similarly to C'sswitch statement. Thewhen statement creates multiple branches of checks, which each evaluated for a particular condition.

when(x){1->print("x == 1")//branch 12->print("x == 2")//branch 2else->{// Note the blockprint("x is neither 1 nor 2")}}
Enter fullscreen modeExit fullscreen mode

when can be used either as an expression or as a statement. If used as an expression, the value of the first matching branch becomes the value of the overall expression. If it is used as a statement, the values of individual branches are ignored.

You can think ofwhen as multipleif-else statements rolled into a more concise format.

For Loop

The Kotlin for loop works like a Cfor each loop rather than Java'sfor loop. It accepts a collection, like an array, and completes the same action on each element of the collection.

The syntax for a 1for loop is:

for(itemincollection)print(item)
Enter fullscreen modeExit fullscreen mode
for(iin1..3){println(i)}
Enter fullscreen modeExit fullscreen mode

While Loop

Thewhile loop executes the body of code repeatedly so long as the listed conditions remain met. Like Java, there are two types ofwhile loop. The standardwhile loop checks for the condition before the code is executed, and thedo-while loop checks after the code is executed.

while(x>0){x--}do{valy=retrieveData()}while(y!=null)// y is visible here!
Enter fullscreen modeExit fullscreen mode

Kotlin Collections

Kotlin includes 3 basic collections: lists, sets, and arrays. Like Java, they each act as frameworks to store data in different ways. Collections are assigned to variables like any other value.

You can create all collections in Kotlin using their unique constructor function. All constructors use the same naming convention,<collection>Of(<value1, value2, …>). For example, you can make a list of 2 integers withlistOf(1, 2).

List

Lists are indexed linear data structure similar to Java arrays. The indices start at0 and go to(list.size - 1). Unlike arrays, lists are dynamic and can resize to accommodate added or removed elements. Lists can contain any number of duplicate elements.

valnumbers=listOf("one","two","three","four")println("Number of elements: ${numbers.size}")println("Third element: ${numbers.get(2)}")println("Fourth element: ${numbers[3]}")println("Index of element \"two\" ${numbers.indexOf("two")}")
Enter fullscreen modeExit fullscreen mode

Sets

A set is an unordered linear data structure that cannot contain duplicate elements. Sets do not have indices. Two sets are considered equal if both contain all the same unique elements.

valnumbers=setOf(1,2,3,4)println("Number of elements: ${numbers.size}")if(numbers.contains(1))println("1 is in the set")valnumbersBackwards=setOf(4,3,2,1)println("The sets are equal: ${numbers == numbersBackwards}")
Enter fullscreen modeExit fullscreen mode

The above sets are equal despite appearing in the opposite order in initialization.

Array

The array is not a native data type in Kotlin. It is represented by the Array class. These arrays behave the same as Java arrays: both contain mutable values but are fixed size.

You can create an array using the functionarrayOf(<element1, element2, …>).

For example:

valpriorities=arrayOf("HIGH","MEDIUM","LOW")println(priorities[1])priorities[1]="NORMAL"println(priorities[1])println(priorities.size)
Enter fullscreen modeExit fullscreen mode

Kotlin Functions

Functions in Kotlin require you to define the function's name, inputs, and outputs. All function definitions begin with thefun keyword and contain a block of code executed when the function is called. Unlike Java, you do not need to define the method asstatic, as Kotlin is less strictly tied to OOP.

Here's an example of Kotlin's function syntax:

fun<variableName>(<inputName>:<inputType>):<returnType>funfibonacci(index:Int):Long
Enter fullscreen modeExit fullscreen mode

To mimic the behavior of Java'svoid return types, you can set the return type toNothing.

One of Kotlin and Java's biggest differences is that functions can exist outside of classes in Kotlin. On the other hand, Java is rigidly bound to object-oriented programming and requires everything to be within class definitions.

Package-level functions (functions outside of any particular class) are used to hold tasks equally useful for any object in the program.
For example, aconvert function that converts kg to lbs and lbs to kg would be a good package-level function because any class in the program might have to convert measurements.

Kotlin also allows for higher-order functions, meaning functions can be passed or returned like other values. This is invaluable forfunctional programming designs.

Extension Functions

Kotlin adapts the standard OOP formula with Extension Functions, which let you extend the functionality of existing classes without inheriting from them. Extension functions are useful when trying to use the functionality of third-party libraries you can't modify but can extend. Unlike inheritance, you can extend a class without full access to it.

For example, you could add additional behavior to an external API that would help closer integrate it with your solution.

To declare an extension function, we need to prefix its name with a receiver type, i.e. the type being extended. The following adds aswap function toMutableList

funMutableList<Int>.swap(index1:Int,index2:Int){valtmp=this[index1]this[index1]=this[index2]this[index2]=tmp}
Enter fullscreen modeExit fullscreen mode

Thethis keyword is used to reference values and methods from the extended type.

Functional Programming with Kotlin

The most significant difference between Kotlin and Java is that Kotlin is tailored for functional programming, not just OOP.Functional programming in Java is limited. While you can mimic many functional behaviors in Java, most developers agree that it's not applicable in the real world.

Kotlin is built from the ground up to be a fully-featured functional language, with higher-order functions, lambda expressions, operator overloading, lazy evaluation, operator overloading, and more.

// higher order functionsfunmain(){valnumbers=arrayListOf(15,-5,11,-39)valnonNegativeNumbers=numbers.filter{it>=0}println(nonNegativeNumbers)//function as input parameter}
Enter fullscreen modeExit fullscreen mode
// lambda expressionvalsum:(Int,Int)->Int={x,y->x+y}funmain(){println(sum(5,10))}
Enter fullscreen modeExit fullscreen mode

What to learn next with Kotlin

Congratulations on taking your first steps with Kotlin! This rising language is perfect for modern developers and is easy to pick up for existing Java developers.

You're now ready to move on to intermediate topics such as:

  • Nullable types

  • Conditions as expressions

  • Map collections

  • Shorthand function notation

  • Operator functions

To help you transition to Kotlin fast, Educative has madeKotlin Crash Course for Programmers. This course is tailored towards existing Java developers, meaning all lessons are hands-on and highlight what's different about the language. By the end, you'll know how to use all the basic features of Kotlin and will be ready to build your first Android application with Android Studio or another Kotlin program

Happy learning!

Continue reading about Kotlin

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Get hands-on with top tech skills. Level up your career.

Level up on in-demand tech skills - at your own speed.

Text-based courses with embedded coding environments help you learn without the fluff.

More fromEducative

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp