đŸ”“
PURPLEBYTEONE
  • main
  • Notes
    • Education
      • Base
        • Information Technology
          • OpenText
            • Courses
              • Security and Forensics
                • EnCaseâ„¢ eDiscovery Series
                  • ED290 - eDiscovery Training with EnCase Information Assurance
                • EnCaseâ„¢ Crossover Series
                  • DFIR450 - EnCase EnScript Programming
                  • DFIR370 - Host Intrusion Methodology and Investigation
                  • DFIR350 - Internet-based Investigations
                  • DFIR130 - EnCase Endpoint Investigator
                • EnCaseâ„¢ Incident Response Series
                  • IR280 - EnCase Endpoint Security
                  • IR250 - Incident Investigation
                • EnCaseâ„¢ Digital Forensics Series
                  • DF420 - Mac Examinations
                  • DF410 - NTFS Examinations
                  • DF320 - Advanced Analysis of Windows Artifacts
                  • DF310 - EnCase Certified Examiner
                  • DF210 - Building an Investigation
                  • DF125 - Mobile Device Examinations
                  • DF120 - Foundations in Digital Forensics
              • Business Network
              • Digital Process Automation
              • Platform Solutions
              • Discovery
              • Digital Experience
              • Analytics
              • Enterprise Content Management
          • Harvard University
            • CS 50
          • LPI
            • Courses
              • Essentials
                • Linux Essentials: 010
                • Security Essentials: 020
                • Web Development Essentials: 030
              • Professional
                • LPIC-1
                  • 101
                  • 102
                • LPIC-2
                  • 201
                  • 202
                • LPIC-3
                  • 300
                  • 303
                  • 305
                  • 306
          • Cloud Orchestration
            • Docker
            • Kubernetes
              • KCNA
              • CKA
              • CKS
          • Google Cloud
            • Path
              • Google Cloud Computing Foundations
              • Network Engineer Learning Path
              • Database Engineer Learning Path
              • Cloud Engineer Learning Path
              • Security Engineer Learning Path
              • Cloud Architect Learning Path
              • Cloud Developer Learning Path
          • VMware
            • Courses
              • Carbon Black
                • Professional
                  • Endpoint Security: Core Technical Skills
                  • App Control Administrator
                  • EDR Administrator
                • Advanced
                  • App Control Advanced Administrator
                  • Advanced Operations and Troubleshooting
                  • Audit and Remediation
                  • Endpoint Standard
                  • Enterprise EDR
                  • EDR Advanced Administrator
                  • EDR Advanced Analyst
          • Amazon
            • Courses
              • Foundation
                • AWS Certified Cloud Practitioner
              • Associate
                • AWS Certified Solutions Architect
              • Professional
                • AWS Certified Solutions Architect
              • Speciality
                • AWS Certified Advanced Networking
                • AWS Certified Security – Specialty
          • Microsoft
            • Courses
              • Azure
                • AZ - 900
                • AZ - 104
                • AZ - 305
                • SC - 900
                • SC - 200
                • SC - 300
                • AZ - 500
                • MS-500
                • SC - 400
                • SC - 100
          • The Code
            • Platform
              • FreeCodeCamp
              • W3
            • Language
              • Python
              • PowerShell
              • JavaScript
              • PHP
              • SQL
              • GO
              • Java
              • Perl
              • Ruby
              • Scala
              • C
              • C#
              • C++
              • Brainfuck
              • CSS
              • JSON
              • Kotlin
              • LOLCODE
              • MISP
              • MongoDB
              • Objective-C
              • Perl
              • Rust
              • SAAS
              • Scala
              • Solidity
              • SWIFT
              • TypeScript
              • WebAssembly
              • XML
              • YAML
              • AngularJS
              • Ansible
              • BASH
              • Docker
              • GIT
              • jQuery
              • VIM
          • OKTA
        • Purple Team
          • Splunk
            • Courses
              • Udemy
            • Notes
          • Security Team Blue
            • Courses
              • BTL v1
              • BTL v2
          • ISC2
            • CC
              • Introduction
              • Security Principles
                • Security Concepts of Information Assurance
                • Risk Management Process
                • Security Controls
                • Governance Elements and Processes
                • Terms and Definitions
              • Incident Response
                • Understand Incident Response
                • Business Continuity
                • Disaster Recovery
              • Access Control Concepts
                • Access Control Concepts
                • Physical Access Controls
                • Logical Access Controls
              • Network Security
                • Computer Networking
                • Threats and Attacks
                • Network Security Infrastructure
              • Security Operations
            • SSCP
            • CISSP
            • CCSP
          • TCM Security
            • Courses
              • Python 101
              • Python 201
              • Linux 101
              • External Pentest Playbook
              • Windows Privilege Escalation
              • Linux Privilege Escalation
              • Movement, Pivoting and Persistence
              • Practical Phishing Assessments
              • Practical Web Application Security
              • Practical Malware Analysis
              • Mobile
              • (OSINT) Fundamentals
              • PEH
            • Certification
              • PNPT
              • PJMR
          • Coursera
            • Courses
              • NYU
                • Introduction to Cyber Security Specialization
              • Google
                • Google Cybersecurity Professional
                  • Foundations of Cybersecurity
                  • Play It Safe: Manage Security Risks
                  • Connect and Protect: Networks and Network Security
                  • Tools of the Trade: Linux and SQL
                  • Assets, Threats, and Vulnerabilities
                  • Sound the Alarm: Detection and Response
                  • Automate Cybersecurity Tasks with Python
                  • Put It to Work: Prepare for Cybersecurity Jobs
          • ICSI Global
          • OccupyTheWeb
            • Courses
              • GSBMH
              • NBFH
              • LBFH
          • CompTIA
            • Courses
              • Core Base
                • A+
                  • Chapter 1
                • Network+
                  • Chapter 1
                • Linux+
                  • Chapter 1
                  • Chapter 2
                • Cloud+
                  • Chapter 1
              • Security
                • Security+
                  • Chapter 1
                    • Risk Terminology
                • Pentest+
                  • Chapter 1
                • CySA+
                  • Chapter 1
                • CSA+
                  • Defending Against Cybersecurity Threats
          • EC-Council
            • Courses
              • CEH
              • CHFI
              • CSA
          • Intel Techniques
            • Courses
              • OSINT Techniques
              • Privacy & Security
          • SANS
            • Courses
              • SEC
                • SEC 401 - Security Essentials
                • SEC 450 - Blue Team Fundamentals
                • SEC 502 - Perimeter Protection In-Depth
                • SEC 503 - Network Monitoring and Threat Detection In-Depth
                • SEC 504 - Hackers Tools, Techniques And Incident Handling
                • SEC 505 - Securing Windows and PowerShell Automation
                • SEC 506 - Securing Linux & UNIX
                • SANS 509 - Securing Oracle Database
                • SEC 511 - Continuous Monitoring and Security Operations
                • SEC 517 - Cutting Edge Hacking Techniques
                • SEC 524 - Cloud Security Fundamentals
                • SEC 531 - Windows Command Line Kung Fu
                • SEC 542 - Web App Penetration Testing
                • SEC 560 - Enterprise Penetration Testing
                • SEC 565 - Red Team Operations and Adversary Emulation
                • SEC 566 - Implementing and Auditing Security Frameworks
                • SEC 573 - Automating Information Security with Python
                • SEC 575: Mobile Device Security
                • SEC 580 - Metasploit for Enterprise Penetration Testing
                • SEC 587 - Advanced Open Source Intelligence
                • SEC 599 - Defeating Advanced Adversaries - Purple Team Tactics & Kill Chain Defenses
                • SEC 617 - Wireless Penetration Testing and Ethical Hacking
                • SEC 642 - Advanced Web App Penetration Testing
                • SEC 660 - Advanced Penetration Testing
                • SEC 760 - Advanced Exploit Development
                • SEC 554: Blockchain and Smart Contract Security
              • FOR
                • FOR 408 - Windows Forensic Analysis
                • FOR 500 - Windows Forensic Analysis
                • FOR 508 - Advanced Digital Forensics and Incident Response
                • FOR 518 - Mac and iOS Forensic Analysis
                • FOR 526 - Memory Forensics In-Depth
                • FOR 572 - Advanced Network Forensics
                • FOR 577 - Virtualization Security Fundamentals
                • FOR 578 - Cyber Threat Intelligence
                • FOR 610 - Reverse-Engineering Malware
                • FOR 710 - Reverse-Engineering Malware: Advanced Code Analysis
              • AUD
                • AUD 507 - Auditing Systems, Applications, and the Cloud
              • ICS
                • ICS 410 - ICS/SCADA Security Essentials
              • MGT
                • MGT 512 - Security Leadership Essentials for Managers
          • IBM
            • Courses
              • Cybersecurity Analyst Professional
                • Introduction to Cybersecurity Tools & Cyber Attacks
                  • Week 1
                  • Week 2
                  • Week 3
                  • Week 4
          • Cybrary
            • Courses
              • SOC L1
              • SOC L2
              • SOC L3
              • Become an Incident Handler
          • Zero Point Security
            • Courses
              • Red Team Ops [CRTO]
              • C2 Development in C#
          • Web Security Academy
            • Courses
              • Burp Suite Certified Practitioner
          • INE
            • Courses
              • eJPT
                • Blue Team
                  • ePND
                  • eCIR
                  • eCRE
                  • ePWD
                  • eCTHPv2
                  • eCDFP
                  • eCMAP
                • Red Team
                  • eMAPT
                  • eWPT
                  • eCPPTv2
                  • eCXD
                  • eWPTXv2
                  • eCPTXv2
          • Pentester Lab
          • Pentester Academy
            • Courses
              • Pentesting with Metasploit: Beginner Edition
              • Linux Privilege Escalation
          • Offensive Security
            • Courses
              • Fundamental
                • Introduction to Secure Software Development
                • Introduction to Cloud Security
                • Exploit Development Essentials
                • Web Application Assessment Essentials
                • Security Operations Essentials
                • Network Penetration Testing Essentials
              • Security Operations
                • SOC-200: Foundational Security Operations and Defensive Analysis (OSDA)
              • Penetration Testing
                • PEN - 200
                • PEN - 210
                • PEN - 300
              • Web Application
                • WEB-200: Foundational Web Application Assessments with Kali Linux (OSWA)
                • WEB-300: Advanced Web Attacks and Exploitation (OSWE)
              • Exploit Development
                • EXP-301: Windows User Mode Exploit Development (OSED)
                • EXP-312: Advanced macOS Control Bypasses (OSMR)
                • EXP-401: Advanced Windows Exploitation (OSEE)
          • Sektor7
            • Courses
              • Windows Privilege Escalation
              • Windows Persistence
              • Malware Development Essentials
              • Evasion Windows Red Team Ops
          • Black Hat
            • Courses
              • BlackHat - Malware Analysis And Memory Forensics
          • Fortinet
          • VHL
          • DFIRdiva
          • YouTube
            • Channels
          • Udemy
            • Certified in Cybersecurity (CC)
            • CompTIA Security+
          • AntiSyphon
          • THM
            • Room
              • SPLUNK
                • Introduction to SIEM
                • Basics
                • Incident handling
                • Investigating
                • Benign
                • ELK 101
                • PS Eclipse
                • New Hire Old Artifacts
                • Conti
                • BOTS
                  • v1
                  • v2
                  • v3
                • ItsyBitsy
            • Learning Paths
              • Introduction to Cyber Security
                • Introduction to Cyber Security
                  • Intro to Offensive Security
                  • Intro to Defensive Security
                • Introduction to Offensive Security
                • Introduction to Defensive Security
          • HTB
            • HTB Academy
              • Job Role Path
                • Penetration Tester
                  • Getting Started
                    • Infosec Overview
                    • Getting Started with a Pentest Distro
                    • Staying Organized
                    • Connecting Using VPN
                    • Common Terms
                  • Machines
                    • Nibbles
                • SOC Analyst
                  • Incident Handling Process
                    • Incident Handling
                    • Cyber Kill Chain
                    • Incident Handling Process Overview
                      • Preparation Stage
                      • Detection & Analysis Stage
                      • Containment, Eradication, & Recovery Stage
                      • Post-Incident Activity Stage
                  • Security Monitoring & SIEM Fundamentals
                  • Windows Event Logs & Finding Evil
                  • Introduction to Threat Hunting & Hunting With Elastic
                  • Understanding Log Sources & Investigating with Splunk
                  • Windows Attacks & Defense
                  • Intro to Network Traffic Analysis
                  • Intermediate Network Traffic Analysis
                  • Working with IDS/IPS
                  • Introduction to Malware Analysis
                  • JavaScript Deobfuscation
                  • YARA & Sigma for SOC Analysts
                  • Introduction to Digital Forensics
                  • Detecting Windows Attacks with Splunk
                  • Security Incident Reporting
            • Challenges
              • Retired
                • Challenges
                  • Hardware
                    • Very Easy
                      • Gawk
                      • Secure Digital
                  • Web
                    • Very Easy
                      • Trapped Source
                  • Mobile
                    • Very Easy
                      • Don't Overreact
                  • Pwn
                    • Very Easy
                      • Getting Started
                      • Questionnaire
                      • Vault-breaker
                  • Crypto
                    • Very Easy
                      • Ancient Encodings
                  • Reverse
                    • Very Easy
                      • WIDE
                      • Shattered Tablet
                      • Hunting License
                      • Gonna-Lift-Em-All
                  • Misc
                    • Very Easy
                      • Compressor
                  • Forensics
                    • Very Easy
                      • Extraterrestrial Persistence
                      • Alien Cradle
                      • Wrong Spooky Season
                  • OSINT
                  • GamePwn
                  • Blockchain
            • Machines
              • Retired
                • Windows
                  • Easy
                    • Blue
          • Blueteamlabs.online
          • LetsDefend.io
          • CyberDefenders.org
      • Infinity
        • c0//53
          • Leet Code
          • Hacker Rank
        • Tools
          • Red Team
            • OSINT
            • Enumeration
            • Web
            • Exploit Base
              • Linux
            • Post-exploitation
              • Backdoor
          • Blue Team
            • Forensics
            • My scripts
        • Bookmarks
          • Cybersecurity
            • Reverse Engineering
            • Telegram
          • MindHub
            • Job Boards
          • GitHub
          • AI
            • Free
          • Books
            • Cybersecurity
              • Linux
                • Linux Essentials For Cybersecurity
                • The Linux Command Line, 2nd Edition: A Complete Introduction
                • How Linux Works, 3rd Edition: What Every Superuser Should Know
              • OSINT
                • Deep Dive: Exploring the Real-world Value of Open Source Intelligence
              • Networking
                • Wireshark for Security Professionals
              • Social Engineering
                • Practical Social Engineering
          • Writeups
    • Carrier
      • Interview Questions
        • General HR questions
        • Cybersecurity
          • Junior Positions
            • SOC L1
            • Junior Malware Analyst
            • Junior Penetration Tester
            • Junior Red Teamer
            • Junior Forensic Analyst
            • Junior Incident responder
            • Junior Threat hunter
            • Junior Security Analyst
          • Specialist Positions
            • SOC L2
            • Malware Analyst
            • Penetration Tester
            • Red Teamer
            • Forensic Analyst
            • Incident responder
            • Threat hunter
            • Security Analyst
          • Senior Positions
            • SOC L3
            • Senior Malware Analyst
            • Senior Penetration Tester
            • Senior Red Teamer
            • Senior Forensic Analyst
            • Senior Incident responder
            • Senior Threat hunter
            • Senior Security Analyst
          • Random questions
            • PT.1
            • PT.2
            • PT.3
            • PT.4
            • PT.5
            • PT.6
    • Note
      • Read
      • Interview
      • Cheat Sheet
        • Penetration Testing
          • Enumeration
  • Roadmap
    • CTF Track
Powered by GitBook
On this page
  1. Notes
  2. Education
  3. Base
  4. Information Technology
  5. The Code
  6. Language

Kotlin

Last updated 1 year ago

Kotlin is a statically typed programming language for the JVM, Android and the browser. It is 100% interoperable with Java.

// Single-line comments start with //
/*
Multi-line comments look like this.
*/

// The "package" keyword works in the same way as in Java.
package com.learnxinyminutes.kotlin

/*
The entry point to a Kotlin program is a function named "main".
The function is passed an array containing any command-line arguments.
Since Kotlin 1.3 the "main" function can also be defined without
any parameters.
*/
fun main(args: Array<String>) {
    /*
    Declaring values is done using either "var" or "val".
    "val" declarations cannot be reassigned, whereas "vars" can.
    */
    val fooVal = 10 // we cannot later reassign fooVal to something else
    var fooVar = 10
    fooVar = 20 // fooVar can be reassigned

    /*
    In most cases, Kotlin can determine what the type of a variable is,
    so we don't have to explicitly specify it every time.
    We can explicitly declare the type of a variable like so:
    */
    val foo: Int = 7

    /*
    Strings can be represented in a similar way as in Java.
    Escaping is done with a backslash.
    */
    val fooString = "My String Is Here!"
    val barString = "Printing on a new line?\nNo Problem!"
    val bazString = "Do you want to add a tab?\tNo Problem!"
    println(fooString)
    println(barString)
    println(bazString)

    /*
    A raw string is delimited by a triple quote (""").
    Raw strings can contain newlines and any other characters.
    */
    val fooRawString = """
fun helloWorld(val name : String) {
   println("Hello, world!")
}
"""
    println(fooRawString)

    /*
    Strings can contain template expressions.
    A template expression starts with a dollar sign ($).
    */
    val fooTemplateString = "$fooString has ${fooString.length} characters"
    println(fooTemplateString) // => My String Is Here! has 18 characters

    /*
    For a variable to hold null it must be explicitly specified as nullable.
    A variable can be specified as nullable by appending a ? to its type.
    We can access a nullable variable by using the ?. operator.
    We can use the ?: operator to specify an alternative value to use
    if a variable is null.
    */
    var fooNullable: String? = "abc"
    println(fooNullable?.length) // => 3
    println(fooNullable?.length ?: -1) // => 3
    fooNullable = null
    println(fooNullable?.length) // => null
    println(fooNullable?.length ?: -1) // => -1

    /*
    Functions can be declared using the "fun" keyword.
    Function arguments are specified in brackets after the function name.
    Function arguments can optionally have a default value.
    The function return type, if required, is specified after the arguments.
    */
    fun hello(name: String = "world"): String {
        return "Hello, $name!"
    }
    println(hello("foo")) // => Hello, foo!
    println(hello(name = "bar")) // => Hello, bar!
    println(hello()) // => Hello, world!

    /*
    A function parameter may be marked with the "vararg" keyword
    to allow a variable number of arguments to be passed to the function.
    */
    fun varargExample(vararg names: Int) {
        println("Argument has ${names.size} elements")
    }
    varargExample() // => Argument has 0 elements
    varargExample(1) // => Argument has 1 elements
    varargExample(1, 2, 3) // => Argument has 3 elements

    /*
    When a function consists of a single expression then the curly brackets can
    be omitted. The body is specified after the = symbol.
    */
    fun odd(x: Int): Boolean = x % 2 == 1
    println(odd(6)) // => false
    println(odd(7)) // => true

    // If the return type can be inferred then we don't need to specify it.
    fun even(x: Int) = x % 2 == 0
    println(even(6)) // => true
    println(even(7)) // => false

    // Functions can take functions as arguments and return functions.
    fun not(f: (Int) -> Boolean): (Int) -> Boolean {
        return {n -> !f.invoke(n)}
    }
    // Named functions can be specified as arguments using the :: operator.
    val notOdd = not(::odd)
    val notEven = not(::even)
    // Lambda expressions can be specified as arguments.
    val notZero = not {n -> n == 0}
    /*
    If a lambda has only one parameter
    then its declaration can be omitted (along with the ->).
    The name of the single parameter will be "it".
    */
    val notPositive = not {it > 0}
    for (i in 0..4) {
        println("${notOdd(i)} ${notEven(i)} ${notZero(i)} ${notPositive(i)}")
    }

    // The "class" keyword is used to declare classes.
    class ExampleClass(val x: Int) {
        fun memberFunction(y: Int): Int {
            return x + y
        }

        infix fun infixMemberFunction(y: Int): Int {
            return x * y
        }
    }
    /*
    To create a new instance we call the constructor.
    Note that Kotlin does not have a "new" keyword.
    */
    val fooExampleClass = ExampleClass(7)
    // Member functions can be called using dot notation.
    println(fooExampleClass.memberFunction(4)) // => 11
    /*
    If a function has been marked with the "infix" keyword then it can be
    called using infix notation.
    */
    println(fooExampleClass infixMemberFunction 4) // => 28

    /*
    Data classes are a concise way to create classes that just hold data.
    The "hashCode"/"equals" and "toString" methods are automatically generated.
    */
    data class DataClassExample (val x: Int, val y: Int, val z: Int)
    val fooData = DataClassExample(1, 2, 4)
    println(fooData) // => DataClassExample(x=1, y=2, z=4)

    // Data classes have a "copy" function.
    val fooCopy = fooData.copy(y = 100)
    println(fooCopy) // => DataClassExample(x=1, y=100, z=4)

    // Objects can be destructured into multiple variables.
    val (a, b, c) = fooCopy
    println("$a $b $c") // => 1 100 4

    // destructuring in "for" loop
    for ((a, b, c) in listOf(fooData)) {
        println("$a $b $c") // => 1 2 4
    }

    val mapData = mapOf("a" to 1, "b" to 2)
    // Map.Entry is destructurable as well
    for ((key, value) in mapData) {
        println("$key -> $value")
    }

    // The "with" function is similar to the JavaScript "with" statement.
    data class MutableDataClassExample (var x: Int, var y: Int, var z: Int)
    val fooMutableData = MutableDataClassExample(7, 4, 9)
    with (fooMutableData) {
        x -= 2
        y += 2
        z--
    }
    println(fooMutableData) // => MutableDataClassExample(x=5, y=6, z=8)

    /*
    We can create a list using the "listOf" function.
    The list will be immutable - elements cannot be added or removed.
    */
    val fooList = listOf("a", "b", "c")
    println(fooList.size) // => 3
    println(fooList.first()) // => a
    println(fooList.last()) // => c
    // Elements of a list can be accessed by their index.
    println(fooList[1]) // => b

    // A mutable list can be created using the "mutableListOf" function.
    val fooMutableList = mutableListOf("a", "b", "c")
    fooMutableList.add("d")
    println(fooMutableList.last()) // => d
    println(fooMutableList.size) // => 4

    // We can create a set using the "setOf" function.
    val fooSet = setOf("a", "b", "c")
    println(fooSet.contains("a")) // => true
    println(fooSet.contains("z")) // => false

    // We can create a map using the "mapOf" function.
    val fooMap = mapOf("a" to 8, "b" to 7, "c" to 9)
    // Map values can be accessed by their key.
    println(fooMap["a"]) // => 8

    /*
    Sequences represent lazily-evaluated collections.
    We can create a sequence using the "generateSequence" function.
    */
    val fooSequence = generateSequence(1, { it + 1 })
    val x = fooSequence.take(10).toList()
    println(x) // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

    // An example of using a sequence to generate Fibonacci numbers:
    fun fibonacciSequence(): Sequence<Long> {
        var a = 0L
        var b = 1L

        fun next(): Long {
            val result = a + b
            a = b
            b = result
            return a
        }

        return generateSequence(::next)
    }
    val y = fibonacciSequence().take(10).toList()
    println(y) // => [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

    // Kotlin provides higher-order functions for working with collections.
    val z = (1..9).map {it * 3}
                  .filter {it < 20}
                  .groupBy {it % 2 == 0}
                  .mapKeys {if (it.key) "even" else "odd"}
    println(z) // => {odd=[3, 9, 15], even=[6, 12, 18]}

    // A "for" loop can be used with anything that provides an iterator.
    for (c in "hello") {
        println(c)
    }

    // "while" loops work in the same way as other languages.
    var ctr = 0
    while (ctr < 5) {
        println(ctr)
        ctr++
    }
    do {
        println(ctr)
        ctr++
    } while (ctr < 10)

    /*
    "if" can be used as an expression that returns a value.
    For this reason the ternary ?: operator is not needed in Kotlin.
    */
    val num = 5
    val message = if (num % 2 == 0) "even" else "odd"
    println("$num is $message") // => 5 is odd

    // "when" can be used as an alternative to "if-else if" chains.
    val i = 10
    when {
        i < 7 -> println("first block")
        fooString.startsWith("hello") -> println("second block")
        else -> println("else block")
    }

    // "when" can be used with an argument.
    when (i) {
        0, 21 -> println("0 or 21")
        in 1..20 -> println("in the range 1 to 20")
        else -> println("none of the above")
    }

    // "when" can be used as an expression that returns a value.
    var result = when (i) {
        0, 21 -> "0 or 21"
        in 1..20 -> "in the range 1 to 20"
        else -> "none of the above"
    }
    println(result)

    /*
    We can check if an object is of a particular type by using the "is" operator.
    If an object passes a type check then it can be used as that type without
    explicitly casting it.
    */
    fun smartCastExample(x: Any) : Boolean {
        if (x is Boolean) {
            // x is automatically cast to Boolean
            return x
        } else if (x is Int) {
            // x is automatically cast to Int
            return x > 0
        } else if (x is String) {
            // x is automatically cast to String
            return x.isNotEmpty()
        } else {
            return false
        }
    }
    println(smartCastExample("Hello, world!")) // => true
    println(smartCastExample("")) // => false
    println(smartCastExample(5)) // => true
    println(smartCastExample(0)) // => false
    println(smartCastExample(true)) // => true

    // Smartcast also works with when block
    fun smartCastWhenExample(x: Any) = when (x) {
        is Boolean -> x
        is Int -> x > 0
        is String -> x.isNotEmpty()
        else -> false
    }

    /*
    Extensions are a way to add new functionality to a class.
    This is similar to C# extension methods.
    */
    fun String.remove(c: Char): String {
        return this.filter {it != c}
    }
    println("Hello, world!".remove('l')) // => Heo, word!
}

// Enum classes are similar to Java enum types.
enum class EnumExample {
    A, B, C // Enum constants are separated with commas.
}
fun printEnum() = println(EnumExample.A) // => A

// Since each enum is an instance of the enum class, they can be initialized as:
enum class EnumExample(val value: Int) {
    A(value = 1),
    B(value = 2),
    C(value = 3)
}
fun printProperty() = println(EnumExample.A.value) // => 1

// Every enum has properties to obtain its name and ordinal(position) in the enum class declaration:
fun printName() = println(EnumExample.A.name) // => A
fun printPosition() = println(EnumExample.A.ordinal) // => 0

/*
The "object" keyword can be used to create singleton objects.
We cannot instantiate it but we can refer to its unique instance by its name.
This is similar to Scala singleton objects.
*/
object ObjectExample {
    fun hello(): String {
        return "hello"
    }

    override fun toString(): String {
        return "Hello, it's me, ${ObjectExample::class.simpleName}"
    }
}


fun useSingletonObject() {
    println(ObjectExample.hello()) // => hello
    // In Kotlin, "Any" is the root of the class hierarchy, just like "Object" is in Java
    val someRef: Any = ObjectExample
    println(someRef) // => Hello, it's me, ObjectExample
}


/* The not-null assertion operator (!!) converts any value to a non-null type and
throws an exception if the value is null.
*/
var b: String? = "abc"
val l = b!!.length

data class Counter(var value: Int) {
    // overload Counter += Int
    operator fun plusAssign(increment: Int) {
        this.value += increment
    }

    // overload Counter++ and ++Counter
    operator fun inc() = Counter(value + 1)

    // overload Counter + Counter
    operator fun plus(other: Counter) = Counter(this.value + other.value)

    // overload Counter * Counter
    operator fun times(other: Counter) = Counter(this.value * other.value)

    // overload Counter * Int
    operator fun times(value: Int) = Counter(this.value * value)

    // overload Counter in Counter
    operator fun contains(other: Counter) = other.value == this.value

    // overload Counter[Int] = Int
    operator fun set(index: Int, value: Int) {
        this.value = index + value
    }

    // overload Counter instance invocation
    operator fun invoke() = println("The value of the counter is $value")

}
/* You can also overload operators through extension methods */
// overload -Counter
operator fun Counter.unaryMinus() = Counter(-this.value)

fun operatorOverloadingDemo() {
    var counter1 = Counter(0)
    var counter2 = Counter(5)
    counter1 += 7
    println(counter1) // => Counter(value=7)
    println(counter1 + counter2) // => Counter(value=12)
    println(counter1 * counter2) // => Counter(value=35)
    println(counter2 * 2) // => Counter(value=10)
    println(counter1 in Counter(5)) // => false
    println(counter1 in Counter(7)) // => true
    counter1[26] = 10
    println(counter1) // => Counter(value=36)
    counter1() // => The value of the counter is 36
    println(-counter2) // => Counter(value=-5)
}

Further Reading

Read more here.
Kotlin tutorials
Try Kotlin in your browser
A list of Kotlin resources