Skip to content

New samples #774

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 14 commits into
base: master
Choose a base branch
from
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,19 @@ interface SoundBehavior {
fun makeSound()
}

class ScreamBehavior(val n:String): SoundBehavior { // 2
class ScreamBehavior(val n: String): SoundBehavior { // 2
override fun makeSound() = println("${n.uppercase()} !!!")
}

class RockAndRollBehavior(val n:String): SoundBehavior { // 2
class RockAndRollBehavior(val n: String): SoundBehavior { // 2
override fun makeSound() = println("I'm The King of Rock 'N' Roll: $n")
}

// Tom Araya is the "singer" of Slayer
class TomAraya(n:String): SoundBehavior by ScreamBehavior(n) // 3
class TomAraya(n: String): SoundBehavior by ScreamBehavior(n) // 3

// You should know ;)
class ElvisPresley(n:String): SoundBehavior by RockAndRollBehavior(n) // 3
class ElvisPresley(n: String): SoundBehavior by RockAndRollBehavior(n) // 3

fun main() {
val tomAraya = TomAraya("Thrash Metal")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,5 @@ fun main() {
}
printLength("Incomprehensibilities")
printLength(1000)
val any = object : Any() {
override fun toString(): String {
return "Any"
}
}
printLength(listOf(any))
printLength(listOf(Any()))
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,5 @@ fun main() {
}
printLength("Incomprehensibilities")
printLength(1000)
val any = object : Any() {
override fun toString(): String {
return "Any"
}
}
printLength(listOf(any))
printLength(listOf(Any()))
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four")
println(numbers.shuffled())
val numbers = listOf("one", "two", "three", "four")
val reversedNumbers = numbers.asReversed()
println(reversedNumbers)
//sampleEnd
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
fun main() {
//sampleStart
val numbers = mutableListOf("one", "two", "three", "four")
val reversedNumbers = numbers.asReversed()
println(reversedNumbers)
numbers.add("five")
println(reversedNumbers)
//sampleEnd
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four")
println(numbers.shuffled())
//sampleEnd
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four")
val sortedStrings = listOf("aaa", "bb", "c", "b", "a", "aa", "ccc")
.sortedWith { a, b ->
when (val compareLengths = a.length.compareTo(b.length)) {
0 -> a.compareTo(b)
else -> compareLengths
}
}

println("Sorted ascending: ${numbers.sorted()}")
println("Sorted descending: ${numbers.sortedDescending()}")
println(sortedStrings)
// [a, b, c, aa, bb, aaa, ccc]
//sampleEnd
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four")
val sortedStrings = listOf("aaa", "bb", "c", "b", "a", "aa", "ccc")
.sortedWith(compareBy<String> { it.length }.thenBy { it })

val sortedNumbers = numbers.sortedBy { it.length }
println("Sorted by length ascending: $sortedNumbers")
val sortedByLast = numbers.sortedByDescending { it.last() }
println("Sorted by the last letter descending: $sortedByLast")
println(sortedStrings)
// [a, b, c, aa, bb, aaa, ccc]
//sampleEnd
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four")
println("Sorted by length ascending: ${numbers.sortedWith(compareBy { it.length })}")

println("Sorted ascending: ${numbers.sorted()}")
println("Sorted descending: ${numbers.sortedDescending()}")
//sampleEnd
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four")
println(numbers.reversed())

val sortedNumbers = numbers.sortedBy { it.length }
println("Sorted by length ascending: $sortedNumbers")
val sortedByLast = numbers.sortedByDescending { it.last() }
println("Sorted by the last letter descending: $sortedByLast")
//sampleEnd
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four")
val reversedNumbers = numbers.asReversed()
println(reversedNumbers)
println("Sorted by length ascending: ${numbers.sortedWith(compareBy { it.length })}")
//sampleEnd
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
fun main() {
//sampleStart
val numbers = mutableListOf("one", "two", "three", "four")
val reversedNumbers = numbers.asReversed()
println(reversedNumbers)
numbers.add("five")
println(reversedNumbers)
val numbers = listOf("one", "two", "three", "four")
println(numbers.reversed())
//sampleEnd
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,10 @@ fun main() {
// You can also use `else if` in expressions:
val maxLimit = 1
val maxOrLimit = if (maxLimit > a) maxLimit else if (a > b) a else b

//sampleEnd

println("max is $max")
// max is 3
println("maxOrLimit is $maxOrLimit")
// maxOrLimit is 3
//sampleEnd
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
fun main() {
//sampleStart
for (i in 1..3) {
println(i)
//sampleStart
val x = 2
when (x) {
1 -> print("x == 1")
2 -> print("x == 2")
else -> print("x is neither 1 nor 2")
}
for (i in 6 downTo 0 step 2) {
println(i)
}
//sampleEnd
// x == 2
//sampleEnd
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
fun main() {
val array = arrayOf("a", "b", "c")
//sampleStart
for (i in array.indices) {
println(array[i])
//sampleStart
val x = 3
when (x) {
// Not all cases are covered
1 -> print("x == 1")
2 -> print("x == 2")
}
//sampleEnd
//sampleEnd
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
fun main() {
val array = arrayOf("a", "b", "c")
//sampleStart
for ((index, value) in array.withIndex()) {
println("the element at $index is $value")
for (i in 1..3) {
print(i)
}
for (i in 6 downTo 0 step 2) {
print(i)
}
// 1236420
//sampleEnd
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
fun main() {
val array = arrayOf("a", "b", "c")
//sampleStart
for (i in array.indices) {
print(array[i])
}
// abc
//sampleEnd
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
fun main() {
val array = arrayOf("a", "b", "c")
//sampleStart
for ((index, value) in array.withIndex()) {
println("the element at $index is $value")
}
// the element at 0 is a
// the element at 1 is b
// the element at 2 is c
//sampleEnd
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//sampleStart
// Creates an abstract class as the base for an exception hierarchy for account-related errors
// Creates a sealed class as the base for an exception hierarchy for account-related errors
sealed class AccountException(message: String, cause: Throwable? = null):
Exception(message, cause)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ data class User(val name: String, val id: Int)
fun main() {
//sampleStart
val user = User("Alex", 1)
val secondUser = User("Alex", 1)
val thirdUser = User("Max", 2)

// Creates an exact copy of user
println(user.copy())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ fun main() {
//sampleStart
val numbers = listOf(1, -2, 3, -4, 5, -6)


val positives = numbers.filter ({ x -> x > 0 })

val isNegative = { x: Int -> x < 0 }
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
class Car(val make: String, val model: String, val numberOfDoors: Int)

fun main() {
//sampleStart
val car1 = Car("Toyota", "Corolla", 4)

// Uses the .toString() function via string templates to print class properties
println("Car1: make=${car1.make}, model=${car1.model}, numberOfDoors=${car1.numberOfDoors}")
// Car1: make=Toyota, model=Corolla, numberOfDoors=4
//sampleEnd
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
abstract class Product(val name: String, var price: Double) {
// Abstract property for the product category
abstract val category: String

// A function that can be shared by all products
fun productInfo(): String {
return "Product: $name, Category: $category, Price: $price"
}
}

class Electronic(name: String, price: Double, val warranty: Int) : Product(name, price) {
override val category = "Electronic"
}

//sampleStart
fun main() {
// Creates an instance of the Electronic class
val laptop = Electronic(name = "Laptop", price = 1000.0, warranty = 2)

println(laptop.productInfo())
// Product: Laptop, Category: Electronic, Price: 1000.0
}
//sampleEnd
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
interface PaymentMethod {
// Functions are inheritable by default
fun initiatePayment(amount: Double): String
}

class CreditCardPayment(val cardNumber: String, val cardHolderName: String, val expiryDate: String) : PaymentMethod {
override fun initiatePayment(amount: Double): String {
// Simulate processing payment with credit card
return "Payment of $$amount initiated using Credit Card ending in ${cardNumber.takeLast(4)}."
}
}

fun main() {
val paymentMethod = CreditCardPayment("1234 5678 9012 3456", "John Doe", "12/25")
println(paymentMethod.initiatePayment(100.0))
// Payment of $100.0 initiated using Credit Card ending in 3456.
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
interface PaymentMethod {
fun initiatePayment(amount: Double): String
}

interface PaymentType {
val paymentType: String
}

class CreditCardPayment(val cardNumber: String, val cardHolderName: String, val expiryDate: String) : PaymentMethod,
PaymentType {
override fun initiatePayment(amount: Double): String {
// Simulate processing payment with credit card
return "Payment of $$amount initiated using Credit Card ending in ${cardNumber.takeLast(4)}."
}

override val paymentType: String = "Credit Card"
}

fun main() {
val paymentMethod = CreditCardPayment("1234 5678 9012 3456", "John Doe", "12/25")
println(paymentMethod.initiatePayment(100.0))
// Payment of $100.0 initiated using Credit Card ending in 3456.

println("Payment is by ${paymentMethod.paymentType}")
// Payment is by Credit Card
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
fun String.bold(): String = "<b>$this</b>"

fun main() {
// "hello" is the receiver object
println("hello".bold())
// <b>hello</b>
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
fun main() {
// Lambda expression with receiver definition
fun StringBuilder.appendText() { append("Hello!") }

// Use the lambda expression with receiver
val stringBuilder = StringBuilder()
stringBuilder.appendText()
println(stringBuilder.toString())
// Hello!
}
Loading
Loading