Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
//sampleStart
fun getStringLength(obj: Any): Int? {
if (obj is String) {
// `obj` is automatically cast to `String` in this branch
return obj.length
}

// `obj` is still of type `Any` outside of the type-checked branch
return null
}
//sampleEnd

fun main() {
fun printLength(obj: Any) {
println("Getting the length of '$obj'. Result: ${getStringLength(obj) ?: "Error: The object is not a string"} ")
}
printLength("Incomprehensibilities")
printLength(1000)
printLength(listOf(Any()))
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
//sampleStart
fun getStringLength(obj: Any): Int? {
// `obj` is automatically cast to `String` on the right-hand side of `&&`
if (obj is String && obj.length >= 0) {
return obj.length
}

return null
}
//sampleEnd

fun main() {
fun printLength(obj: Any) {
println("Getting the length of '$obj'. Result: ${getStringLength(obj) ?: "Error: The object is not a string"} ")
}
printLength("Incomprehensibilities")
printLength("")
printLength(1000)
}

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
fun main() {
fun main() {
//sampleStart
open class Shape
class Rectangle: Shape()

fun Shape.getName() = "Shape"
fun Rectangle.getName() = "Rectangle"

fun printClassName(s: Shape) {
println(s.getName())
}

printClassName(Rectangle())
//sampleEnd
}
// builder is an instance of StringBuilder
val builder = StringBuilder()
// Calls .appendLine() extension function on builder
.appendLine("Hello")
.appendLine()
.appendLine("World")
println(builder.toString())
// Hello
//
// World
}
//sampleEnd
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
fun main() {
//sampleStart
data class Order(val weight: Double)
val calculateShipping = fun Order.(rate: Double): Double = this.weight * rate

val order = Order(2.5)
val cost = order.calculateShipping(3.0)
println("Shipping cost: $cost")
// Shipping cost: 7.5
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
fun main() {
val isInRange: Int.(min: Int, max: Int) -> Boolean = { min, max -> this in min..max }

println(5.isInRange(1, 10))
// true
println(20.isInRange(1, 10))
// false
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
data class User(val firstName: String, val lastName: String)

// An extension property to get a username-style email handle
val User.emailUsername: String
get() = "${firstName.lowercase()}.${lastName.lowercase()}"

fun main() {
val user = User("Mickey", "Mouse")
// Calls extension property
println("Generated email username: ${user.emailUsername}")
// Generated email username: mickey.mouse
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
data class House(val streetName: String)

// Doesn't compile because there is no getter and setter
// var House.number = 1
// Error: Initializers are not allowed for extension properties

// Compiles successfully
val houseNumbers = mutableMapOf<House, Int>()
var House.number: Int
get() = houseNumbers[this] ?: 1
set(value) {
println("Setting house number for ${this.streetName} to $value")
houseNumbers[this] = value
}

fun main() {
val house = House("Maple Street")

// Shows the default
println("Default number: ${house.number} ${house.streetName}")
// Default number: 1 Maple Street

house.number = 99
// Setting house number for Maple Street to 99

// Shows the updated number
println("Updated number: ${house.number} ${house.streetName}")
// Updated number: 99 Maple Street
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
class Logger {
companion object { }
}

fun Logger.Companion.logStartupMessage() {
println("Application started.")
}

fun main() {
Logger.logStartupMessage()
// Application started.
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
class Host(val hostname: String) {
fun printHostname() { print(hostname) }
}

class Connection(val host: Host, val port: Int) {
fun printPort() { print(port) }

// Host is the extension receiver
fun Host.printConnectionString() {
// Calls Host.printHostname()
printHostname()
print(":")
// Calls Connection.printPort()
// Connection is the dispatch receiver
printPort()
}

fun connect() {
/*...*/
// Calls the extension function
host.printConnectionString()
}
}

fun main() {
Connection(Host("kotl.in"), 443).connect()
// kotl.in:443

// Triggers an error because the extension function isn't available outside Connection
// Host("kotl.in").printConnectionString()
// Unresolved reference 'printConnectionString'.
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
open class User

class Admin : User()

open class NotificationSender {
open fun User.sendNotification() {
println("Sending user notification from normal sender")
}

open fun Admin.sendNotification() {
println("Sending admin notification from normal sender")
}

fun notify(user: User) {
user.sendNotification()
}
}

class SpecialNotificationSender : NotificationSender() {
override fun User.sendNotification() {
println("Sending user notification from special sender")
}

override fun Admin.sendNotification() {
println("Sending admin notification from special sender")
}
}

fun main() {
// Dispatch receiver is NotificationSender
// Extension receiver is User
// Resolves to User.sendNotification() in NotificationSender
NotificationSender().notify(User())
// Sending user notification from normal sender

// Dispatch receiver is SpecialNotificationSender
// Extension receiver is User
// Resolves to User.sendNotification() in SpecialNotificationSender
SpecialNotificationSender().notify(User())
// Sending user notification from special sender

// Dispatch receiver is SpecialNotificationSender
// Extension receiver is User NOT Admin
// The notify() function declares user as type User
// Statically resolves to User.sendNotification() in SpecialNotificationSender
SpecialNotificationSender().notify(Admin())
// Sending user notification from special sender
}
Loading
Loading