kotlinlang.org Open in urlscan Pro
13.227.219.29  Public Scan

Submitted URL: http://fuckjava.com/
Effective URL: https://kotlinlang.org/
Submission: On November 17 via api from US — Scanned from NL

Form analysis 0 forms found in the DOM

Text Content

The Kotlin Developer Survey is underway! Share your experience to help us make
the language even better! →
v1.9.20
 * Solutions
   * Multiplatform
   * Server-side
   * Data science
   * Android
 * Docs
 * Community
 * Teach
 * Play
   * Playground
   * Examples
   * Koans


CONCISE. CROSS‑PLATFORM. FUN.

Get started

Developed by JetBrains & Open-source Contributors


MULTIPLATFORM

Share code on your terms and for different platforms


SERVER-SIDE

Modern development experience with familiar JVM technology


MULTIPLATFORM LIBRARIES

Create a library that works across several platforms


ANDROID

Recommended by Google for building Android apps

Data Science


LATEST FROM KOTLIN



blog.jetbrains.com


KOTLINCONF 2024 TICKETS ARE NOW AVAILABLE! ↗

kotlinlang.org


UPDATED KOTLIN ROADMAP FOR 2023 ↗

blog.jetbrains.com


KOTLIN MULTIPLATFORM MOBILE CONTENT CREATORS ↗

blog.jetbrains.com


REPRODUCIBLE KOTLIN COMPILER ARTIFACTS ↗

Kotlin blog ↗
Simple
Asynchronous
Object-oriented
Functional
Ideal for tests
Run

fun main() {
    val name = "stranger"        // Declare your first variable
    println("Hi, $name!")        // ...and use it!
    print("Current count:")
    for (i in 0..10) {           // Loop over a range from 0 to 10
        print(" $i")
    }
}

xxxxxxxxxx



 

fun main() {

    val name = "stranger"        // Declare your first variable

    println("Hi, $name!")        // ...and use it!

    print("Current count:")

    for (i in 0..10) {           // Loop over a range from 0 to 10

        print(" $i")

    }

}




Open in Playground →
Target: JVMRunning on v.1.9.20

import kotlinx.coroutines.*

suspend fun main() {                                // A function that can be suspended and resumed later
    val start = System.currentTimeMillis()
    coroutineScope {                                // Create a scope for starting coroutines
        for (i in 1..10) {
            launch {                                // Start 10 concurrent tasks
                delay(3000L - i * 300)              // Pause their execution
                log(start, "Countdown: $i")
            }
        }
    }
    // Execution continues when all coroutines in the scope have finished
    log(start, "Liftoff!")
}

fun log(start: Long, msg: String) {
    println("$msg " +
            "(on ${Thread.currentThread().name}) " +
            "after ${(System.currentTimeMillis() - start)/1000F}s")
}

xxxxxxxxxx



 

import kotlinx.coroutines.*

​

suspend fun main() {                                // A function that can be suspended and resumed later

    val start = System.currentTimeMillis()

    coroutineScope {                                // Create a scope for starting coroutines

        for (i in 1..10) {

            launch {                                // Start 10 concurrent tasks

                delay(3000L - i * 300)              // Pause their execution

                log(start, "Countdown: $i")

            }

        }

    }

    // Execution continues when all coroutines in the scope have finished

    log(start, "Liftoff!")

}

​

fun log(start: Long, msg: String) {

    println("$msg " +

            "(on ${Thread.currentThread().name}) " +

            "after ${(System.currentTimeMillis() - start)/1000F}s")

}




Open in Playground →
Target: JVMRunning on v.1.9.20

abstract class Person(val name: String) {
    abstract fun greet()
}

interface FoodConsumer {
    fun eat()
    fun pay(amount: Int) = println("Delicious! Here's $amount bucks!")
}

class RestaurantCustomer(name: String, val dish: String) : Person(name), FoodConsumer {
    fun order() = println("$dish, please!")
    override fun eat() = println("*Eats $dish*")
    override fun greet() = println("It's me, $name.")
}

fun main() {
    val sam = RestaurantCustomer("Sam", "Mixed salad")
    sam.greet() // An implementation of an abstract function
    sam.order() // A member function
    sam.eat()   // An implementation of an interface function
    sam.pay(10) // A default implementation in an interface
}

xxxxxxxxxx



 

abstract class Person(val name: String) {

    abstract fun greet()

}

​

interface FoodConsumer {

    fun eat()

    fun pay(amount: Int) = println("Delicious! Here's $amount bucks!")

}

​

class RestaurantCustomer(name: String, val dish: String) : Person(name), FoodConsumer {

    fun order() = println("$dish, please!")

    override fun eat() = println("*Eats $dish*")

    override fun greet() = println("It's me, $name.")

}

​

fun main() {

    val sam = RestaurantCustomer("Sam", "Mixed salad")

    sam.greet() // An implementation of an abstract function

    sam.order() // A member function

    sam.eat()   // An implementation of an interface function

    sam.pay(10) // A default implementation in an interface

}




Open in Playground →
Target: JVMRunning on v.1.9.20

fun main() {
    // Who sent the most messages?
    val frequentSender = messages
        .groupBy(Message::sender)
        .maxByOrNull { (_, messages) -> messages.size }
        ?.key                                                 // Get their names
    println(frequentSender) // [Ma]

    // Who are the senders?
    val senders = messages
        .asSequence()                                         // Make operations lazy (for a long call chain)
        .filter { it.body.isNotBlank() && !it.isRead }        // Use lambdas...
        .map(Message::sender)                                 // ...or member references
        .distinct()
        .sorted()
        .toList()                                             // Convert sequence back to a list to get a result
    println(senders) // [Adam, Ma]
}

data class Message(                                           // Create a data class
    val sender: String,
    val body: String,
    val isRead: Boolean = false,                              // Provide a default value for the argument
)

val messages = listOf(                                        // Create a list
    Message("Ma", "Hey! Where are you?"),
    Message("Adam", "Everything going according to plan today?"),
    Message("Ma", "Please reply. I've lost you!"),
)

xxxxxxxxxx



 

fun main() {

    // Who sent the most messages?

    val frequentSender = messages

        .groupBy(Message::sender)

        .maxByOrNull { (_, messages) -> messages.size }

        ?.key                                                 // Get their names

    println(frequentSender) // [Ma]

​

    // Who are the senders?

    val senders = messages

        .asSequence()                                         // Make operations lazy (for a long call chain)

        .filter { it.body.isNotBlank() && !it.isRead }        // Use lambdas...

        .map(Message::sender)                                 // ...or member references

        .distinct()

        .sorted()

        .toList()                                             // Convert sequence back to a list to get a result

    println(senders) // [Adam, Ma]

}

​

data class Message(                                           // Create a data class

    val sender: String,

    val body: String,

    val isRead: Boolean = false,                              // Provide a default value for the argument

)

​

val messages = listOf(                                        // Create a list

    Message("Ma", "Hey! Where are you?"),

    Message("Adam", "Everything going according to plan today?"),

    Message("Ma", "Please reply. I've lost you!"),

)




Open in Playground →
Target: JVMRunning on v.1.9.20

// Tests
// The following example works for JVM only
import org.junit.Test
import kotlin.test.*

class SampleTest {
    @Test
    fun `test sum`() {                  // Write test names with whitespaces in backticks
        val a = 1
        val b = 41
        assertEquals(42, sum(a, b), "Wrong result for sum($a, $b)")
    }

    @Test
    fun `test computation`() {
        assertTrue("Computation failed") {
            setup()                     // Use lambda returning the test subject
            compute()
        }
    }
}

// Sources
fun sum(a: Int, b: Int) = a + b
fun setup() {}
fun compute() = true

xxxxxxxxxx



 

// Tests

// The following example works for JVM only

import org.junit.Test

import kotlin.test.*

​

class SampleTest {

    @Test

    fun `test sum`() {                  // Write test names with whitespaces in backticks

        val a = 1

        val b = 41

        assertEquals(42, sum(a, b), "Wrong result for sum($a, $b)")

    }

​

    @Test

    fun `test computation`() {

        assertTrue("Computation failed") {

            setup()                     // Use lambda returning the test subject

            compute()

        }

    }

}

​

// Sources

fun sum(a: Int, b: Int) = a + b

fun setup() {}

fun compute() = true




Open in Playground →
Target: JUnitRunning on v.1.9.20
Get started ↗
Concise
Safe
Expressive
Asynchronous
Interoperable
Run

// More than 30% fewer lines of code compared to Java
// (based on the experience of Duolingo and other companies)

data class Book (
    val title: String,                         // + automatically generated equals(),
    val year: Int                              // hashCode(), toString(), and copy()
)
fun century(year: Int) = (year - 1) / 100 + 1  // Top-level function,
                                               // single-expression body
fun main() {
    val books = listOf(                        // Construct a list
        Book("Don Quixote", 1605),             // No `new` keyword
        Book("The Lord of the Rings", 1955)
    )
    val classics = books.filter { century(it.year) < 20 } // Trailing single-argument lambda
    println("Classic books: $classics")                   // Calls toString() for Book
}

// More than 30% fewer lines of code compared to Java







Open in Playground →
Target: JVMRunning on v.1.9.20

// Apps built with Kotlin are 20% less likely to crash
// (based on Google's internal data)

fun printMessagesUppercased(messages: List<String?>) { // List elements can be nulls
    // messages.add(Message("Java"))                   // ERROR: List is read-only
    messages.onEachIndexed { index, msg ->
        print("\nMessage #$index: ")
        // print(msg.uppercase())                      // ERROR: `msg` can be null
        msg?.let {                                     // Print only if `msg` is not null
            print(it.uppercase())                      // OK, `it` is String
        }
    }
}
fun main() {
    val messages = mutableListOf("hello", null, "world")
    // messages = mutableListOf("!!!")                 // ERROR: can't reassign a value
    messages.add("Kotlin")                             // OK: the list is mutable
    printMessagesUppercased(messages)                  // Pass the list as read-only
}

// Apps built with Kotlin are 20% less likely to crash







Open in Playground →
Target: JVMRunning on v.1.9.20

import kotlin.math.absoluteValue

fun main() {
//sampleStart
    val dates = listOf(1 to "January", 13 to "May", 22 to "September", 23 to "December")
    dates.forEach { (day, month) ->                 // Traverse a list of pairs with a trailing lambda
        println("${day.ordinal()} of $month")       // Use the Int.ordinal() extension function
    }
    createEmptyWindow()
        .apply {                                    // Configure properties of an object
            width = 300
            height = 200
            isVisible = true
        }.also { w ->                               // Perform an additional operation on a call chain
            showWindow(w)
        }
    issueById["13456"]
        ?.takeIf { it.status == Status.FIXED }      // Use the value only if the condition is true
        ?.let {                                     // Do something only if the value is not null
            println("We've fixed this: $it")
        }
//sampleEnd
}

// Extension function
fun Int.ordinal() = this.absoluteValue.let { iAbs ->
    val suffix = if (iAbs % 100 in 11..13) "th" else
        when (iAbs % 10) {
            1 -> "st"
            2 -> "nd"
            3 -> "rd"
            else -> "th"
        }
    "$this$suffix"
}
data class Window(var width: Int, var height: Int, var isVisible: Boolean)
fun createEmptyWindow() = Window(0, 0, false)
fun showWindow(window: Window) {
    println("Showing $window")
}
enum class Status { OPEN, FIXED, IN_PROGRESS }
data class Issue(val status: Status)
val issueById = mutableMapOf(
    "13456" to Issue(Status.FIXED)
)

dates.forEach { (day, month) ->                 // Traverse a list of pairs with a trailing lambda







Open in Playground →
Target: JVMRunning on v.1.9.20

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

//sampleStart
// More than 50% of professional developers who use coroutines
// report increased productivity
// (based on Google's internal data)

fun main() = runBlocking {
    val start = System.currentTimeMillis()
    coroutineScope {                                 // Create a scope for coroutines
        val waitingJob = launch {                    // Launching a coroutine
            waiting(start, 150)
        }
        countdownSignals(10, 300).collect { value -> // Collecting flow elements
            log(start, "Countdown: $value")
        }
        waitingJob.cancel()                          // Cancelling a coroutine
    }
    log(start, "Liftoff!")                           // Execution continues when all
}                                                    // coroutines have finished
//sampleEnd
fun countdownSignals(n: Int, delayMillis: Long): Flow<Int> = flow { // Flow builder
    for (i in (1..n).reversed()) {
        delay(delayMillis)                           // Delay in emitting signals
        emit(i)                                      // Emit the flow element
    }
}

// A function that can be suspended and resumed later
suspend fun waiting(start: Long, delayMillis: Long) {
    while (currentCoroutineContext().isActive) {     // Check coroutine's context
        log(start, "Waiting...")
        delay(delayMillis)                           // Waiting concurrently
    }
}

fun log(start: Long, msg: String) {
    println("$msg after ${(System.currentTimeMillis() - start)/1000F}s")
}

// More than 50% of professional developers who use coroutines







Open in Playground →
Target: JVMRunning on v.1.9.20

// Use any existing JVM library or framework
// Call Kotlin code from Java without an issue

@SpringBootApplication
class DemoApplication

fun main(args: Array<String>) {
    runApplication<DemoApplication>(*args)
}

@RestController
class MessageResource {
    @GetMapping
    fun index(): List<Message> = listOf(
        Message("1", "Hello!"),
        Message("2", "Bonjour!"),
        Message("3", "Privet!"),
    )
}

data class Message(val id: String?, val text: String)

// Use any existing JVM library or framework







Get started ↗


SHARE CODE ON YOUR TERMS AND FOR DIFFERENT PLATFORMS

Simplify the development of cross-platform projects with Kotlin Multiplatform.
It reduces time spent writing and maintaining the same code for different
platforms while retaining the flexibility and benefits of native programming.
Kotlin applications will work on different operating systems, such as iOS,
Android, macOS, Windows, Linux, watchOS, and others.


Learn about Kotlin Multiplatform → Learn more →


BIG, FRIENDLY AND HELPFUL
COMMUNITY

Kotlin has great support and many contributors in its fast-growing global
community. Enjoy the benefits of a rich ecosystem with a wide range of community
libraries. Help is never far away — consult extensive community resources or ask
the Kotlin team directly.


Join the community →


KOTLIN USAGE HIGHLIGHTS


GRADLE

Gradle is introducing Kotlin as a language for writing build scripts


CORDA

Corda is an open-source distributed ledger platform, supported by major banks,
and built entirely in Kotlin


EVERNOTE

Evernote recently integrated Kotlin into their Android client


COURSERA

Coursera Android app is partially written in Kotlin


SPRING

Spring makes use of Kotlin's language features to offer more concise APIs


ATLASSIAN

All new code in the Trello Android app is in Kotlin

Want to give it a try?


START USING KOTLIN TODAY!
BUILD YOUR FIRST APP IN YOUR FAVORITE IDE

Get started
Stay in touch:

 * Contributing to Kotlin
 * Releases
 * Press Kit
 * Security
 * Blog
 * Issue Tracker
 * Brand assets
 * Careers

Kotlin™ is protected under the Kotlin Foundation and licensed under the Apache
2 license.
Supported and developed by JetBrains

Our website uses some cookies and records your IP address for the purposes of
accessibility, security, and managing your access to the telecommunication
network. You can disable data collection and cookies by changing your browser
settings, but it may affect how this website functions. Learn more.

With your consent, JetBrains may also use cookies and your IP address to collect
individual statistics and provide you with personalized offers and ads subject
to the Privacy Policy and the Terms of Use. JetBrains may use third-party
services for this purpose. You can adjust or withdraw your consent at any time
by visiting the Opt-Out page.

[A]ccept All[M]anage Settings