Auto Added by WPeMatico

Kotlin in Education

More developers are choosing Kotlin every day. It is one of the fastest-growing programming languages according to GitHub, and one of the most in-demand coding languages according to Hired

As demand for Kotlin developers increases, we are looking to support computer science educators and make Kotlin educational content as widely available as possible. 

In this post, we’d like to share with you the current state of Kotlin in education, the benefits of including it in academic curricula, and the resources and initiatives we have for educators.


State of Kotlin in academia

Since Kotlin’s conception, both industry and academia have taken a liking to the language, and it continues to evolve to meet the demands of these sectors. Kotlin is used by top companies, including Google, Twitter, Reddit, Netflix, Uber, BMW, Coursera, Slack, and Trello, just to name a few. With major companies buying into Kotlin, universities are also seeing it as a prospective career for their students.

Over 190 universities already teach Kotlin, including 25 of the top 100 ranked universities in the Times Higher Education Rankings in 2021.

Reach out to us at education@kotlinlang.org if you’d like to have your university featured on our map.

Among the Kotlin courses we know about, we are seeing educators teach topics like introduction to programming, Android application development, software engineering, languages and compilers, object-oriented programming, and functional programming.


Benefits of teaching Kotlin

What makes Kotlin a good fit for teaching? Let’s take a look at the reasons why educators choose it and why it’s a great teaching tool that helps students succeed in computer science.

Modern, concise, and safe syntax

One of Kotlin’s core goals is to let programmers express exactly what they mean. By being a concise language, Kotlin allows students to focus on expressing their ideas, rather than writing boilerplate code. Less code written also means fewer opportunities for error and less code to test, debug, and grade. Kotlin also promotes writing correct programs with static type checking, automatic memory management, and null safety. 

Multiplatform

The first-choice language for Android development, Kotlin is also being adopted for teaching multiplatform development for mobile, web, server-side programming, data science, and other computer science topics.

Interoperability

Kotlin is 100% interoperable with Java and can rely on a wealth of existing Java libraries. If you already have Java code, you can call it directly from Kotlin code, and vice versa. You can even auto-convert existing Java code (or course materials) to Kotlin with our helpful Java-to-Kotlin converter, halving the amount of code. You get all the benefits of a modern programming language with minimal migration work.

Kotlin can also be compiled to JavaScript to run in the browser or on Node.js, or into a standalone native binary targeting any major operating system. 

Supports object-oriented and functional programming

Kotlin combines imperative, procedural, object-oriented, and functional programming, making it a general-purpose and multiparadigm language.

Easy to learn

According to many Kotlin educators, the language’s concise syntax makes it a perfect tool for explaining fundamental programming concepts. It has an easy learning curve and builds on the students’ previous programming experience, being especially simple to grasp for those with a Java or Python background.


Our resources and initiatives

If you are interested in learning and teaching Kotlin, there are a lot of ways to get up and running.

Tooling

JetBrains has built several dozen products that cover all stages of the software development cycle and all major technologies and programming languages. Many top software engineering tools are packaged with Kotlin, so both you and your students will never be left without tooling and infrastructure support for Kotlin.

  • Free educational licenses for IntelliJ IDEA Ultimate for immersing your students into the workflows of millions of professional developers.
  • Java-to-Kotlin converter – the IDE can automatically translate your code from Java to Kotlin.
  • Playground for trying out small code snippets in the browser. 
  • EduTools plugin with existing interactive courses and the ability to create custom ones.
  • Code With Me – a new service for collaborative coding and pair programming. 

Kotlinlang.org/education

Check out all our teaching resources at kotlinlang.org/education, including:

Kotlinlang Slack 

If you want to get a feel for the community and talk to other people working with and on Kotlin, then the Kotlinlang Slack is the right place. With more than 39,000 members and a 

dedicated #education channel, it is the first place to look for other educators and people interested in furthering Kotlin in education.

Kotlin YouTube channel

Subscribe to the official YouTube channel Kotlin by JetBrains and join our monthly educational webinars by educators and for educators, alongside a plethora of other Kotlin content!

Watch the recent episode of the Talking Kotlin show, where we talk about the role of Kotlin in teaching:

Kotlin in competitive programming

The language is being developed by a team that includes multiple competitive programming champions. Competitions are a great way to practice the language, which is why we hold our own quarterly Kotlin Heroes contest designed for participants of all levels. Before each contest, we open a practice round with open solutions, so you can practice powerful language features and see some hints if you get stuck.

Open source community

Kotlin is supported by, and evolves with the help of, its diverse community. Join the conversation with peers in our community groups:

If you are teaching Kotlin or are interested in launching a course that involves Kotlin, do reach out to us! We want to hear from you, answer your questions, and help you with anything you might need for your teaching objectives. 

Please post your feedback, questions, and suggestions in the comments below or share them with us at education@kotlinlang.org. 

Let’s teach Kotlin!

Continue ReadingKotlin in Education

Idiomatic Kotlin: Solving Advent of Code Puzzles, Day 2

Let’s continue learning how to write idiomatic Kotlin code by solving the Advent of Code tasks! Today, we’re discussing the solution for the day 2 task.

Day 2. Password philosophy

We need to confirm that passwords meet the corporate policy. Find the full task description at https://adventofcode.com/2020/day/2*.

First, we need to read the input:

1-3 a: abcde
1-3 b: cdefg
2-9 c: ccccccccc

Each line contains the password policy and the password. Our task is to check that the password is valid and conforms to the given policy. The policies are different in the first and the second parts of the task.

In the first part, the password policy indicates the lowest and highest number of times a given letter must appear for the password to be valid. For example,

1-3 a

means that the password must contain

a

at least once and at most 3 times. In the example, two passwords, the first and the third ones, are valid. The first contains one

a

, and the third contains nine

c

s, both within the limits of their respective policies. The second password,

cdefg

, is invalid, as it contains no instances of

b

but needs at least 1.

In the second part, the policy describes two positions in the password, where 1 means the first character, 2 means the second character, and so on (indexing starts at 1, not 0). Exactly one of these positions must contain the given letter. Other occurrences of the letter are irrelevant. Given the same example list from above:

  1. 1-3 a: abcde

    is valid: position 1 contains

    a

    and position 3 does not.

  2. 1-3 b: cdefg

    is invalid: neither position 1 nor position 3 contains

    b

    .

  3. 2-9 c: ccccccccc

    is invalid: both positions 2 and position 9 contain

    c

    .

We should count the number of passwords from the given input that are valid according to the interpretations of the policies.

As usual, if you haven’t done it, please solve the task yourself first. Here’s how you can set up Kotlin for this purpose.

Solution

First, we should read and parse the input. Let’s create a

data

class for storing a given password together with its policy:

data class PasswordWithPolicy(
   val password: String,
   val range: IntRange,
   val letter: Char
)

Each policy specifies an integer range and a letter that we store in the

IntRange

and

Char

types, accordingly. The modifier

data

instructs the compiler to generate some useful methods for this class, including the constructor,

equals

,

hashCode

, and

toString

.

Parsing input

Let’s write a function that parses one input line into this class. Since it’s a function that creates an instance, let’s put it into a companion object in our data class. Then we can call it by the class name:

PasswordWithPolicy.parse()

.

data class PasswordWithPolicy(...) {
   companion object {
       fun parse(line: String): PasswordWithPolicy { 
           TODO()
       }
   }
}

While developing, you can put the

TODO()

call that throws the

NotImplementedError

exception. Because it returns the

Nothing

type, which is a subtype of any other type, the compiler won’t complain. The function is supposed to return

PasswordWithPolicy

, but throwing an exception inside is totally valid from the compiler’s point of view.

There are two ways to parse the input: by using utility functions on Strings or by using regular expressions. Let’s discuss both of these ways.

The Kotlin standard library contains many useful functions on

String

s, including

substringAfter()

and

substringBefore()

which perfectly solve the task in our case:

// 1-3 a: abcde
fun parse(line: String) = PasswordWithPolicy(
   password = line.substringAfter(": "),
   letter = line.substringAfter(" ").substringBefore(":").single(),
   range = line.substringBefore(" ").let {
       val (start, end) = it.split("-")
       start.toInt()..end.toInt()
   },
)

We provide the parameter names explicitly while calling the

PasswordWithPolicy

constructor. The input format convention requires that:

  • password

    be the string that goes right after the colon

  • the letter go between the whitespace and the colon, and
  • the range go before the whitespace and consist of two numbers split by “
    -

To build a range, we first take the substring before the whitespace and split it with the “

-

” delimiter. We then use only the first two parts (

start

and

end

), and build a range using the “

..

” operator converting both lines to

Int

s. We use

let

to convert the result of

substringBefore()

to the desired range.

In this code, we assume that all the input lines follow the rules. In a real-world scenario, we should check that the input is correct.

substringAfter()

and similar functions take a second argument default to the string itself that should be returned in the event the given delimiter is not found.

toInt()

and

single()

have

toIntOrNull()

and

singleOrNull()

counterparts returning

null

if the string can’t be converted to an integer number or consists of more than one character.

Let’s now implement the same logic using regular expressions. Here is a regular expression describing the input format:

(d+)-(d+) ([a-z]): ([a-z]+)

First are two numbers split by -, then a letter and a password.

Our new

parse

function matches the line against a regular expression and then builds

PasswordWithPolicy

on the result:

private val regex = Regex("""(d+)-(d+) ([a-z]): ([a-z]+)""")
fun parseUsingRegex(line: String): PasswordWithPolicy =
   regex.matchEntire(line)!!
       .destructured
       .let { (start, end, letter, password) ->
           PasswordWithPolicy(password, start.toInt()..end.toInt(), letter.single())
       }

In Kotlin, you use the

Regex

class to define a regular expression. Note how we put it inside a triple-quoted string, so you don’t need to escape

 

. For regular strings, escaping is done in the conventional way, with a backslash, so if you need a backslash character in the string, you repeat it:

"(\d+)-(\d+)".

We assume that our input is correct, which is why we use

!!

to throw an NPE if the input doesn’t correspond to the regular expression. An alternative is to use the safe access

?.

here and return

null

as the result.

The

destructured

property provides components for a destructuring assignment for groups defined in the regular expression. We use its result together with

let

and destruct it inside the lambda expression, defining

start

,

end

,

letter

, and

password

as parameters. As before, we need to convert strings to

Int

s and

Char

.

Password validation

After we read the input, we need to validate whether the passwords comply with the given policy.

In the first part, we need to ensure that the number of occurrences of a given letter is in a range. It’s one line in Kotlin:

data class PasswordWithPolicy(
   val password: String,
   val range: IntRange,
   val letter: Char
) {
   fun validatePartOne() =
       password.count { it == letter } in range
   ...
}

We count the occurrences of

letter

in the

password

string, and check that the result is in

range

.

in

checks that the given element belongs to a range. For numbers and other comparable elements,

x in range

is the same as writing explicitly

range.first <= x && x <= range.last

.

The second part isn’t difficult. We need to check that exactly one of the positions (stored in the range) contains the given letter. We use the boolean

xor

operator for that, which returns

true

if the operands are different. That’s exactly what we need here:

fun validatePartTwo() =
   (password[range.first - 1] == letter) xor (password[range.last - 1] == letter)

We need to subtract 1 from

first

and

last

because they imply indexing from one, but string indexation starts from zero.

Added all together, this gives us our

main

function that finds the result for both parts:

fun main() {
   val passwords = File("src/day2/input.txt")
       .readLines()
       .map(PasswordWithPolicy::parse)
   println(passwords.count { it.validatePartOne() })
   println(passwords.count { it.validatePartTwo() })
}

Note how we pass a member reference

PasswordWithPolicy::parse

to the

map

function to convert the strings to passwords.

That’s it! We discussed how to solve this problem, and along the way, looked at string utility functions, regular expressions, operations on collections, and how

let

helps transform the expression nicely to the form you need.

Please let us know if you find this format useful and would like us to provide solutions for more difficult tasks!

*Used with the permission of Advent of Code (Eric Wastl).

Continue ReadingIdiomatic Kotlin: Solving Advent of Code Puzzles, Day 2

Solving Advent of Code Puzzles in Idiomatic Kotlin

What’s the best way to learn a language other than writing some code with it? Solving fun and short tasks like the ones from Advent of Code might be a great opportunity to practice your language skills, and you can learn a lot if you compare your solutions with how others have solved the same problem.

Lots of developers from around the world, including some from the Kotlin team, take part in the Advent of Code challenges created by Eric Wastl. Advent of Code is a series of tasks published every December, which you solve and compete with others. Many would agree that it’s the best advent calendar to celebrate Christmas and New Year!

To help the community learn idiomatic Kotlin, and motivate more developers to solve Advent of Code tasks in Kotlin in the future, we decided to prepare solutions for the tasks from Advent of Code 2020. It doesn’t matter if you solved it back in December, you’re ready to solve it now, or you just want to check the solutions – we hope you’ll find something useful in these materials. Of course, it works best if you try to solve the same task first yourself!

Below is the solution and video for the first task. If you find this format useful and want us to cover more tasks in a similar fashion, please share in the comments!

Day 1. Report Repair

We’re fixing an expense report! Find the full task description at https://adventofcode.com/2020/day/1*.

You need to find the two (and in the second part, three) entries from the list of numbers that sum to 2020 and then multiply those two (or three) numbers together.

How to solve the task

Register at https://adventofcode.com/, open the task at https://adventofcode.com/2020/day/1, write your solution in Kotlin, and check the result on the site. You can either write Kotlin code online or using an IDE:

Finally, compare your solution with the solution below.

We marked the

src

folder as a source set to put the code directly there. We copied input files, like

src/day1/input.txt

, to the source folder for convenience. You can find the solutions in this project.

Solution

Here’s the sample input:

1721
979
366
299
675
1456

First, we need to read and parse the input. We can use the Kotlin

readLines()

function for reading a list of lines from a given file:

File("src/day1/input.txt").readLines()

The

readLines()

returns a list of Strings, and we convert it to a list of numbers:

import java.io.File
fun main() {
   val numbers = File("src/day1/input.txt")
       .readLines()
       .map(String::toInt)


}

You put this code inside the

main

function, the entry point for your program. When you start typing, IntelliJ IDEA imports the

java.io.File

automatically.

Now we can simply iterate through the list, and then for each number repeat the iteration and check the sum:

for (first in numbers) {
   for (second in numbers) {
       if (first + second == 2020) {
           println(first * second)
           return
       }
   }
}

You put this code inside

main

, so

return

returns from

main

when the required numbers are found.

In a similar way, you check the sum of three numbers:

for (first in numbers) {
   for (second in numbers) {
       for (third in numbers) {
           if (first + second + third == 2020) {
               println(first * second * third)
               return
           }
       }
   }
}

You can run it and get the result for a given input. That’s it! The first task is really a simple one.

However, we iterate over the same list again and again for each of the elements. Having two nested loops for finding two numbers makes it N2 operations, where N is the number of elements. When we need to find three numbers, that’s three nested loops, and N3 operations. If the list of numbers is large, that’s not the most efficient way to solve this type of problem. Surely there is a better way, right?

There definitely is and the Kotlin standard library can help us express that concisely. As often happens, we can replace the long calculation with some kind of smart storage used to find the result.

Solving the task for two numbers

First, let’s build a map for number “complements” – numbers that together with the given number sum up to 2020:

val complements = numbers.associateBy { 2020 - it }

We use the Kotlin

associateBy

function to build the map. Its lambda argument returns a key in this map, by which the list element is getting stored. For the sample input it’ll be the following map:

numbers: [1721, 979, 366, 299, 675, 1456]
complements map: {299=1721, 1041=979, 1654=366, 1721=299, 1345=675, 564=1456}

After this procedure, you can clearly see the answer! The very first number

1721

from the list is present in the

complements

map as a key:

1721=299

, which means it’s the complement for the number

299

, and they sum to

2020

.

Having stored this information in a map, we can check if any number from the list has a complement in this map. The following code finds the first number with an existing complement:

val pair = numbers.mapNotNull { number ->
   val complement = complements[number]
   if (complement != null) Pair(number, complement) else null
}.firstOrNull()

We transform each number into a pair consisting of the number and its complement (if the complement exists) and then find the first non-null result.

We use

mapNotNull

, which transforms each element in a list and filters out all the resulting

null

s. It’s shorthand for calling first

map

, and then

filterNotNull

on the result.

firstOrNull

returns the first element in the list or

null

if the list is empty. Kotlin standard library often uses the

OrNull

suffix to mark functions returning

null

on failure rather than throwing an exception (like

elementAtOrNull

,

singleOrNull

, or

maxOrNull

).

Starting with Kotlin 1.5.0, you can also replace the two consequent operations

mapNotNull

and

first(OrNull)

with one function call:

firstNotNullOf(OrNull)

.

After building the auxiliary structure, we managed to find the resulting two numbers in N operations, not in N2 as before!

We need a multiplication of these numbers, so here’s the last step:

println(pair?.let { (a, b) -> a * b })

The

pair

variable contains a nullable

Pair

of two numbers and is

null

if the initial list contains no numbers that sum up to 2020. We use safe access

?.

together with the

let

function and destructuring in a lambda syntax to display the result in case

pair

is not

null

.

Solving the task for three numbers

The next step is solving this problem for three numbers. Let’s reuse what we’ve done so far and extract the logic of finding a pair of numbers summing up to a given number into a separate function:

fun List<Int>.findPairOfSum(sum: Int): Pair<Int, Int>? {
   // Map: sum - x -> x
   val complements = associateBy { sum - it }
   return firstNotNullOfOrNull { number ->
       val complement = complements[number]
       if (complement != null) Pair(number, complement) else null
   }
}

We also used the

firstNotNullOfOrNull

function.

Now, we use

findPairOfSum

to build a helper map that stores the complement pair of values for each number which together with this number sums up to 2020:

// Map: x -> (y, z) where y + z = 2020 - x
val complementPairs: Map<Int, Pair<Int, Int>?> =
   numbers.associateWith { numbers.findPairOfSum(2020 - it) }

For the same initial input, here’s the complement pairs map:

numbers: [1721, 979, 366, 299, 675, 1456]
complement pairs: {1721=null, 979=(366, 675), 366=(979, 675), 299=null, 675=(979, 366), 1456=null}

As before, you already can see the answer! It’s the number that corresponds to a non-null pair in a map.

However, we don’t really need to build the whole map — we only need to find the first number that corresponds to a non-null pair! Let’s find it using the already familiar

firstNotNullOfOrNull

function:

fun List<Int>.findTripleOfSum(): Triple<Int, Int, Int>? =
   firstNotNullOfOrNull { x ->
       findPairOfSum(2020 - x)?.let { pair ->
           Triple(x, pair.first, pair.second)
       }
   }

Note Kotlin’s concise syntax – the function can return an expression directly.

The final step is to find the multiplication if the resulting triple is non-null, similar to how we did it before:

println(triple?.let { (x, y, z) -> x * y * z} )

That’s all!

In the next part, we’ll discuss how to solve the second task. Please let us know if you find this content useful and would like us to provide solutions for more tasks!

*Used with the permission of Advent of Code (Eric Wastl).

Continue ReadingSolving Advent of Code Puzzles in Idiomatic Kotlin

Why Learn Kotlin?

Kotlin has always been and continues to be a modern language in the industry, addressing the real needs of real developers. It is increasingly being adopted in many trending fields, including mobile, web, server-side and cloud development, data science, and education.

This all gives a strong indication that there is already significant demand for Kotlin developers and there will continue to be in the future.

So where can you start learning this skill? “Atomic Kotlin”!

This book is suited for Kotlin learners of all levels, and it is available in print and as an ebook. It breaks Kotlin programming language concepts into atoms, and provides hands-on exercises inside IntelliJ IDEA.

To celebrate the recent release of “Atomic Kotlin”, we asked our Twitter community to share their motivation for learning Kotlin. You all did not disappoint! There were a lot of great responses from the community, and we saw a couple of patterns emerging. In this post, we are going to share with you some of the answers people gave about why Kotlin is a great language to learn.

Buy your copy

Modern Language

Kotlin is a modern programming language that combines all the best bits of imperative, object-oriented, and functional programming. It is general-purpose and multi-paradigm, and conciseness and safety are some of the language’s key features.

Easy to Learn

Kotlin’s syntax is simple to grasp for beginners, while at the same time, the language offers sophisticated powerful features for experienced programmers.

Kotlin can build on the learners’ previous programming experience. It is simple to grasp for those with a Java or Python background. Kotlin’s syntax is also easy to learn for iOS developers because it is based on the same modern concepts they are already familiar with.

Great Materials

There is a lot of up-to-date material available to help you learn Kotlin. One of our favorite resources for learning Kotlin from scratch is “Atomic Kotlin”. Readers can see their progress while solving the tasks that are checked automatically within IntelliJ IDEA. There are hints and solutions to help them out if they get stuck. All the examples in “Atomic Kotlin” are available in this GitHub repository. You can compile, run, and test the examples which are automatically extracted directly from the book.

Buy your copy

You can learn what the authors of “Atomic Kotlin”, Bruce Eckel and Svetlana Isakova, think about learning the language in this episode of the JetBrains Connect series. In it, they discuss the question of why to learn Kotlin, with host Paul Everitt:

Multiplatform

As a language that supports multiplatform targets, you can run Kotlin on virtually any device these days, be it a PC or a Mac, and also as native code. This means you can build mobile, web frontend, and backend applications with Kotlin as well.

In addition to being the official language for Android development, Kotlin is a proven technology for building cross-platform mobile applications. It eliminates all the disadvantages of other leading approaches and lets you create mobile apps with native performance and UIs while sharing the business logic completely. Visit the Kotlin Multiplatform Mobile portal to learn more.

Progression from Java

Kotlin’s interoperability allows it to be introduced seamlessly anywhere you’re already using Java. Kotlin fixes some of the issues Java suffers from and has some features that are absent from Java.

Career prospects

Many great companies already use Kotlin to build their products, and Kotlin skills are increasingly in demand as more and more businesses are adopting the language. Indeed, the number of Kotlin job postings has skyrocketed by 1400% since 2017 (Source: Dice).

Community Driven

Since its very beginning in 2011, Kotlin has been developed as an open-source language.

Kotlin evolves with the help of our diverse community, which includes almost 200 Kotlin User Groups, 37K+ Kotlinlang Slack users, and countless other members spread across our forum, our sub-Reddit, YouTube, Twitter, and many other platforms. Over 450 contributors are working on Kotlin, including 90 JetBrains developers.

Your feedback provides the basis for our roadmap. Thank you for your continued support!

Why did you Learn Kotlin?

If you haven’t already taken up Kotlin, we hope that this post has left you feeling inspired to do so. We would love to hear about your own motivations for learning Kotlin in the comments below. If you share your story with us, you will also have the chance to win an “Atomic Kotlin” ebook! We’ll select 5 winners from the commenters to this post on May 12.

Continue ReadingWhy Learn Kotlin?

End of content

No more pages to load