Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Kotlin 1.1 tour

Sponsored · Ship Features Fearlessly Turn features on and off without deploys. Used by thousands of Ruby developers.

Kotlin 1.1 tour

Avatar for きりみん

きりみん

April 02, 2017
Tweet

More Decks by きりみん

Other Decks in Programming

Transcript

  1. Bound callable references val numbers = listOf("abc", "123", "456")
 


    // 1.1Ͱग़དྷΔΑ͏ʹͳͬͨ͜ͱɹଞͷม਺ͷؔ਺ࢀর
 val numberRegex = "\\d+".toRegex()
 numbers.filter(numberRegex::matches)
 // 1.0Ͱ΋ग़དྷͨ͜ͱୡ fun isAbc(str: String) = str.equals("abc", true)
 numbers.filter(::isAbc)
 numbers.map(String::toUpperCase)
 numbers.filter { numberRegex.matches(it) }
  2. Sealed and data classes sealed class Express
 
 // ExpressͷαϒΫϥεΛExpressͱฒྻʹએݴ


    class Const(val number: Double) : Express()
 
 // dataΫϥε͸ଞͷΫϥεΛܧঝ͕Մೳʹ // sealedΫϥεͷαϒΫϥεʹ΋ग़དྷ·͢
 data class Sum(val e1: Express, val e2: Express) : Express()
  3. Destructuring Declarations val map = mapOf(1 to "one", 2 to

    "two")
 // ࠓ·Ͱ͸Ҿ਺ΛҰ౓ड͚͔ͯΒ෼ׂએݴ͢Δඞཁ͕͋ͬͨ
 map.map { entry ->
 val (key, value) = entry
 "$key -> $value!"
 }
 
 // 1.1Ͱ͸௚઀keyͱvalueΛ෼ׂએݴ͢Δࣄ͕Մೳʹ map.map { (key, value) -> "$key -> $value!" }
  4. Underscores in numeric literals val oneMillion = 1_000_000
 val hexBytes

    = 0xFF_EC_DE_5E
 val bytes = 0b11010010_01101001_10010100_10010010
  5. Shorter syntax for properties data class Person(val name: String, val

    age: Int) {
 // 1.1Ͱग़དྷΔΑ͏ʹͳͬͨ͜ͱ
 val isAdult get() = age >= 20 // Property type inferred to be 'Boolean'
 
 // 1.0·Ͱ͸ܕએݴ͕ඞཁͩͬͨ
 val isChild : Boolean get() = age < 20
 
 // ͜Ε͸1.0Ͱ΋ਪ࿦ͯ͘͠Εͨ
 val isBaby = age < 5
 }
  6. Inline property accessors val <T> List<T>.lastIndex: Int
 inline get() =

    this.size - 1 inline val <T> List<T>.lastIndex: Int
 get() = this.size - 1
  7. Local delegated properties val answer by lazy {
 println("Calculating the

    answer...")
 1 + 1
 }
 if (needAnswer()) { // answer͸͜͜ͰॳΊͯܭࢉ͞ΕΔ
 println("The answer is $answer.") 
 } else { // ͜ͷ৔߹͸answer͸ܭࢉ͞Εͳ͍
 println("Sometimes no answer is the answer...")
 }
  8. Generic enum value access enum class RGB { RED, GREEN,

    BLUE }
 
 // EnumΛδΣωϦΫεͱͯ͠डऔΓશͯͷ஋ͷnameΛग़ྗ͢Δؔ਺
 inline fun <reified T : Enum<T>> printAllValues() {
 print(enumValues<T>().joinToString { it.name })
 }
 
 fun printAllRGBColor() {
 printAllValues<RGB>()
 }