SlideShare a Scribd company logo
😎




😁
package demo
class Person(val name: String, val age: Int? = null) {
override fun toString(): String {
return "name=$name, age=$age"
}
}
fun main(args: Array<String>) {
val persons = listOf(Person(" "), Person(" ", age = 30))
val oldest = persons.maxBy { it.age ?: 0 }
println(" $oldest")
}
// name= , age=30
package demo;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
public final class Person {
private String name;
private Integer age = null;
public Person(String name) {
this.name = name;
}
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "name=" + name + ", age=" + age;
}
public static void main(String[] args) {
List<Person> persons = Arrays.asList(
new Person(" "), new Person(" ", 30));
Optional<Person> oldest = persons.stream()
.max(Comparator.comparing(p -> p.age == null ? 0 : p.age));
System.out.println(" " + oldest.orElse(null));
}
// name= , age=30
}




if
while
for 



import java.util.Random
fun main(args: Array<String>) {
//
val rand = Random()
val a = rand.nextBoolean()
val b = rand.nextBoolean()
//
if (a == b) {
println("A B ")
} else {
println("A B ")
}
//
while (rand.nextBoolean() != a) {
print(" ")
}
println(" !")
}
// ( )
// A B
// !
// 2
println(if (a == b) "A B " else "A B ")
for (i in listOf("a", "b", "c")) {
println(i)
}
for (s in listOf("a", "b", "c").withIndex()) {
println(s.index)
println(s.value)
}


default else
import java.util.Random
fun main(args: Array<String>) {
// when 1
when (Random().nextBoolean()) {
true -> println(" ")
false -> println(" ")
}
// when 2
println(when (Random().nextBoolean()) {
true -> " "
false -> " "
})
// when
val num = Random().nextInt()
when {
num > 0 -> println("0 ")
num < 0 -> println("0 ")
else -> println(" !")
}
}
fun ( : , …) { }
fun ( : , …): { }
//
fun max(a: Int, b: Int): Int = if (a > b) a else b
//
fun min(a: Int, b: Int): Int {
return if (a > b) b else a
}
val var
//
val question = " "
//
val answer: Int = 42
//
var foo = "foo"
fun update() {
foo = "bar" //
}
Byte, Short, Int, Long,

Float, Double, Char, Boolean
String
Object Void
Any, Unit, Nothing
//
val ints: Set<Int> = setOf(100, -1, 1_000_000)
val longs: Set<Long> = setOf(100L, -1L)
val doubles: Set<Double> = setOf(0.12, 2.0, 1.2e10, 1.2e-10)
val floats: Set<Float> = setOf(123.4f, .456F, 1e3f)
val chars: Set<Char> = setOf('a', 't', 'u0009')
val hexValues: Set<Long> = setOf(0xCAFEBABE, 0xbcdL)
val binValues: Set<Long> = setOf(0B0, 0b000000101)
val booleans: Set<Boolean> = setOf(true, false)
$value
${statement}
fun main(args: Array<String>) {
val name = if (args.isNotEmpty()) args[0] else "Kotlin"
println("Hello, $name!")
println("Hello, ${name.toUpperCase()}!")
val rawString = """
<html>
<body>
Hello, $name
</body>
</html>
""".trimIndent()
println(rawString)
}
// Hello, Kotlin!
// Hello, KOTLIN!
// <html>
// <body>
// Hello, Kotlin
// </body>
// </html>
trimIndent()
Type? Type null
NullPointerException 

fun main(args: Array<String>) {
val x: String? = null
// val y: String = x // !
val len = if (x != null) x.length else 0 // : if-then x null
println(len)
// 0
}
fun ops() {
var n = 1 - 1 * 1 / 1 % 1 // (plus, minus, times, div, mod)
n += 1 // (plusAssign)
-n++ // (unaryMinus, inc)
val b = n == 1 // (equals)
val m = mapOf("one" to 1, "two" to 2)
val e = m["one"] // (index)
val i = "two" in m // in (contains)
val l = 1..100 // (rangeTo)
}
fun mustPerson(a: Any): Person {
return a as Person // as - ClassCastException
}
fun mayPerson(a: Any) {
val p: Person? = a as? Person // as? - null
val pMsg: String? = p?.toString() // ?. - (null + )
println(pMsg ?: " ") // ?: - (null )
}
Int
shl, shr, ushr,
and, or, xor, inv
operator
infix
class Point3D(val x: Int, val y: Int, val z: Int)
open class Point2D(val x: Int, val y: Int) {
// +
operator fun plus(other: Point2D): Point2D {
return Point2D(x + other.x, y + other.y)
}
// infix
infix fun addZ(z: Int): Point3D {
return Point3D(x, y, z)
}
}
fun main(args: Array<String>) {
val p1 = Point2D(5, 10)
val p2 = p1 + Point2D(2, 2)
val p3 = p2 addZ 1 // , p2.addZ(1)
println("${p3.x}, ${p3.y}, ${p3.z}")
// 7, 12, 1
}
MutableCollection
MutableIterable
val itemNullable: Set<Int?> = setOf(1, 2, null) // null
val listNullable: Set<Int>? = null // null
val bothNullable: Set<Int?>? = setOf(1, 2, null) // null
init 





super() {}
// , Java public final class User1 {}
class User1
// ( )
class User2(val nickname: String)
//
class User3(_nickname: String) {
val nickname = _nickname
}
// constructor
class User4 private constructor(_nickname: String) {
val nickname = _nickname
}
// ( )
class User5 {
constructor(nickname: String) {
println(nickname)
}
constructor(nickname: String, enabled: Boolean) {
println("$nickname (enabled=$enabled)")
}
}
class User1 {
init {
println(" ")
}
}
open, final, abstract, override final
final open final
public, internal, protected, private public
internal
class Person(
val name: String, // , getter
private val age: Int, // , getter
var isMarried: Boolean // , getter, setter
)
class Rectangle(val height: Int, val width: Int) {
val isSquare: Boolean
get() { // getter
return height == width
}
}
equals
hashCode
toString
data class User(val id: Long, val name: String, private val address: List<String>)
fun main(args: Array<String>) {
val user = User(1L, " ", listOf(" ", " "))
if (user.id != 1L) throw InternalError()
println(user)
}
// User(id=1, name= , address=[ , ])
interface
: InterfaceName
interface Clickable {
fun click() //
fun showOff() = println(" !") //
}
class Button : Clickable {
override fun click() = println(" ")
}
abstract fun
abstract class
open
SubClass : SuperClass()

abstract class Animated {
// override
abstract fun animate()
// override
open fun stopAnimating() {
}
// override
fun animateTwice() {
}
}
class AnimatedImpl : Animated() {
override fun animate() {
println("animating")
}
override fun stopAnimating() {
println("override")
}
}


by
interface Base {
fun print()
}
class BaseImpl(val x: Int) : Base {
override fun print() = print(x)
}
class Derived(b: Base) : Base by b // Derived Base
fun main(args: Array<String>) {
val b = BaseImpl(10)
Derived(b).print() // 10
}
// ( + )
object Payroll {
val allEmployees = arrayListOf<Person>()
fun calculateSalary() {
// ...
}
}
fun main(args: Array<String>) {
val window = JWindow()
window.addMouseListener(
// (Java )
object : MouseAdapter() {
override fun mouseClicked(e: MouseEvent) {
println(" !")
}
override fun mouseEntered(e: MouseEvent) {
println(" !")
}
}
)
}




serialVersionUID
Companion
class A {
companion object {
const val foo = "hoge"
fun bar() {
println(" ")
}
}
}
fun main(args: Array<String>) {
println(A.foo)
A.bar()
}
// Java
public class Main {
public static void main(String[] args) {
System.out.println(A.foo);
A.Companion.bar();
}
}
companion object Loader {
fun fromJSON(json: String): Person = …
}




IOException
Closable
use close 

// try-catch-finally
fun readNumber(reader: BufferedReader): Int? {
val number = try {
Integer.parseInt(reader.readLine())
} catch (e: NumberFormatException) {
null
} finally {
reader.close()
}
return number
}
// use { try-catch } (Java try-with-resources )
fun readNumber2(reader: BufferedReader): Int? {
return reader.use {
try {
Integer.parseInt(it.readLine())
} catch (e: NumberFormatException) {
null
}
}
}
import javax.swing.JButton;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
// Java
public class Lambda {
public static void main(String[] args) {
JButton button = new JButton();
//
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Action performed");
}
});
//
button.addActionListener(e -> System.out.println("Action performed"));
}
}
import javax.swing.JButton
fun main(args: Array<String>) {
val button = JButton()
button.addActionListener { e ->
println("Action performed")
}
}


it
data class Person(val name: String, val age: Int)
fun findTheOldest(people: List<Person>): Person? {
var maxAge = 0
var theOldest: Person? = null
for (person in people) {
if (person.age > maxAge) {
maxAge = person.age
theOldest = person
}
}
return theOldest
}
fun main(args: Array<String>) {
val people = listOf(Person("Alice", 29), Person("Bob", 31))
println(findTheOldest(people)) //
println(people.maxBy { person -> person.age }) //
println(people.maxBy { it.age }) // (it )
}
val sum = { x: Int, y: Int -> x + y }
Iterable
fun twoAndThree(operation: (Int, Int) -> Int) { //
val result = operation(2, 3) //
println(" $result")
}
fun main(args: Array<String>) {
twoAndThree { a, b -> a + b } // 5
twoAndThree { a, b -> a * b } // 6
}
let, with, run, apply,
also
this apply,
with, run
it also, let
fun main(args: Array<String>) {
val person = Person() //
person.name = " "
person.setDateOfBirth(1988, 4, 12)
val person2 = Person().apply { // apply
name = " "
setDateOfBirth(1988, 4, 12)
}
val person3 = Person().also { // also
it.name = " "
it.setDateOfBirth(1988, 4, 12)
}
val person4 = with(Person()) { // with
name = " "
setDateOfBirth(1988, 4, 12)
}
person.name?.let { println(it) } // name null let
person.name?.run { println(this) } // name null run
}
import


BigDecimal
import java.io.PrintWriter
import java.io.StringWriter
fun Exception.stackTraceString(): String {
val sw = StringWriter()
PrintWriter(sw).use { printStackTrace(it) }
return sw.toString()
}
fun main(args: Array<String>) {
println(RuntimeException().stackTraceString())
}


かとうの Kotlin 講座 こってり版

More Related Content

What's hot

Functional pe(a)rls: Huey's zipper
Functional pe(a)rls: Huey's zipperFunctional pe(a)rls: Huey's zipper
Functional pe(a)rls: Huey's zipper
osfameron
 
Is Haskell an acceptable Perl?
Is Haskell an acceptable Perl?Is Haskell an acceptable Perl?
Is Haskell an acceptable Perl?
osfameron
 
Pre-Bootcamp introduction to Elixir
Pre-Bootcamp introduction to ElixirPre-Bootcamp introduction to Elixir
Pre-Bootcamp introduction to Elixir
Paweł Dawczak
 
Functional Pe(a)rls - the Purely Functional Datastructures edition
Functional Pe(a)rls - the Purely Functional Datastructures editionFunctional Pe(a)rls - the Purely Functional Datastructures edition
Functional Pe(a)rls - the Purely Functional Datastructures edition
osfameron
 
Poly-paradigm Java
Poly-paradigm JavaPoly-paradigm Java
Poly-paradigm Java
Pavel Tcholakov
 
First few months with Kotlin - Introduction through android examples
First few months with Kotlin - Introduction through android examplesFirst few months with Kotlin - Introduction through android examples
First few months with Kotlin - Introduction through android examples
Nebojša Vukšić
 
Kotlin from-scratch 2 - functions
Kotlin from-scratch 2 - functionsKotlin from-scratch 2 - functions
Kotlin from-scratch 2 - functions
Franco Lombardo
 
Probabilistic Programming in Scala
Probabilistic Programming in ScalaProbabilistic Programming in Scala
Probabilistic Programming in Scala
BeScala
 
Groovy puzzlers jug-moscow-part 2
Groovy puzzlers jug-moscow-part 2Groovy puzzlers jug-moscow-part 2
Groovy puzzlers jug-moscow-part 2
Evgeny Borisov
 
Inteligencia artificial 4
Inteligencia artificial 4Inteligencia artificial 4
Inteligencia artificial 4
Nauber Gois
 
ES6, WTF?
ES6, WTF?ES6, WTF?
ES6, WTF?
James Ford
 
Scala in practice
Scala in practiceScala in practice
Scala in practice
andyrobinson8
 
Programming Lisp Clojure - 2장 : 클로저 둘러보기
Programming Lisp Clojure - 2장 : 클로저 둘러보기Programming Lisp Clojure - 2장 : 클로저 둘러보기
Programming Lisp Clojure - 2장 : 클로저 둘러보기
JangHyuk You
 
The groovy puzzlers (as Presented at JavaOne 2014)
The groovy puzzlers (as Presented at JavaOne 2014)The groovy puzzlers (as Presented at JavaOne 2014)
The groovy puzzlers (as Presented at JavaOne 2014)
GroovyPuzzlers
 
The Ring programming language version 1.3 book - Part 36 of 88
The Ring programming language version 1.3 book - Part 36 of 88The Ring programming language version 1.3 book - Part 36 of 88
The Ring programming language version 1.3 book - Part 36 of 88
Mahmoud Samir Fayed
 
Exhibition of Atrocity
Exhibition of AtrocityExhibition of Atrocity
Exhibition of Atrocity
Michael Pirnat
 
The Ring programming language version 1.5.3 book - Part 46 of 184
The Ring programming language version 1.5.3 book - Part 46 of 184The Ring programming language version 1.5.3 book - Part 46 of 184
The Ring programming language version 1.5.3 book - Part 46 of 184
Mahmoud Samir Fayed
 
Lecture on Rubinius for Compiler Construction at University of Twente
Lecture on Rubinius for Compiler Construction at University of TwenteLecture on Rubinius for Compiler Construction at University of Twente
Lecture on Rubinius for Compiler Construction at University of Twente
Dirkjan Bussink
 
Elixir & Phoenix – fast, concurrent and explicit
Elixir & Phoenix – fast, concurrent and explicitElixir & Phoenix – fast, concurrent and explicit
Elixir & Phoenix – fast, concurrent and explicit
Tobias Pfeiffer
 
Elixir & Phoenix – fast, concurrent and explicit
Elixir & Phoenix – fast, concurrent and explicitElixir & Phoenix – fast, concurrent and explicit
Elixir & Phoenix – fast, concurrent and explicit
Tobias Pfeiffer
 

What's hot (20)

Functional pe(a)rls: Huey's zipper
Functional pe(a)rls: Huey's zipperFunctional pe(a)rls: Huey's zipper
Functional pe(a)rls: Huey's zipper
 
Is Haskell an acceptable Perl?
Is Haskell an acceptable Perl?Is Haskell an acceptable Perl?
Is Haskell an acceptable Perl?
 
Pre-Bootcamp introduction to Elixir
Pre-Bootcamp introduction to ElixirPre-Bootcamp introduction to Elixir
Pre-Bootcamp introduction to Elixir
 
Functional Pe(a)rls - the Purely Functional Datastructures edition
Functional Pe(a)rls - the Purely Functional Datastructures editionFunctional Pe(a)rls - the Purely Functional Datastructures edition
Functional Pe(a)rls - the Purely Functional Datastructures edition
 
Poly-paradigm Java
Poly-paradigm JavaPoly-paradigm Java
Poly-paradigm Java
 
First few months with Kotlin - Introduction through android examples
First few months with Kotlin - Introduction through android examplesFirst few months with Kotlin - Introduction through android examples
First few months with Kotlin - Introduction through android examples
 
Kotlin from-scratch 2 - functions
Kotlin from-scratch 2 - functionsKotlin from-scratch 2 - functions
Kotlin from-scratch 2 - functions
 
Probabilistic Programming in Scala
Probabilistic Programming in ScalaProbabilistic Programming in Scala
Probabilistic Programming in Scala
 
Groovy puzzlers jug-moscow-part 2
Groovy puzzlers jug-moscow-part 2Groovy puzzlers jug-moscow-part 2
Groovy puzzlers jug-moscow-part 2
 
Inteligencia artificial 4
Inteligencia artificial 4Inteligencia artificial 4
Inteligencia artificial 4
 
ES6, WTF?
ES6, WTF?ES6, WTF?
ES6, WTF?
 
Scala in practice
Scala in practiceScala in practice
Scala in practice
 
Programming Lisp Clojure - 2장 : 클로저 둘러보기
Programming Lisp Clojure - 2장 : 클로저 둘러보기Programming Lisp Clojure - 2장 : 클로저 둘러보기
Programming Lisp Clojure - 2장 : 클로저 둘러보기
 
The groovy puzzlers (as Presented at JavaOne 2014)
The groovy puzzlers (as Presented at JavaOne 2014)The groovy puzzlers (as Presented at JavaOne 2014)
The groovy puzzlers (as Presented at JavaOne 2014)
 
The Ring programming language version 1.3 book - Part 36 of 88
The Ring programming language version 1.3 book - Part 36 of 88The Ring programming language version 1.3 book - Part 36 of 88
The Ring programming language version 1.3 book - Part 36 of 88
 
Exhibition of Atrocity
Exhibition of AtrocityExhibition of Atrocity
Exhibition of Atrocity
 
The Ring programming language version 1.5.3 book - Part 46 of 184
The Ring programming language version 1.5.3 book - Part 46 of 184The Ring programming language version 1.5.3 book - Part 46 of 184
The Ring programming language version 1.5.3 book - Part 46 of 184
 
Lecture on Rubinius for Compiler Construction at University of Twente
Lecture on Rubinius for Compiler Construction at University of TwenteLecture on Rubinius for Compiler Construction at University of Twente
Lecture on Rubinius for Compiler Construction at University of Twente
 
Elixir & Phoenix – fast, concurrent and explicit
Elixir & Phoenix – fast, concurrent and explicitElixir & Phoenix – fast, concurrent and explicit
Elixir & Phoenix – fast, concurrent and explicit
 
Elixir & Phoenix – fast, concurrent and explicit
Elixir & Phoenix – fast, concurrent and explicitElixir & Phoenix – fast, concurrent and explicit
Elixir & Phoenix – fast, concurrent and explicit
 

Similar to かとうの Kotlin 講座 こってり版

Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlin
intelliyole
 
Kotlin killed Java stars
Kotlin killed Java starsKotlin killed Java stars
Kotlin killed Java stars
Matteo Bonifazi
 
Scala - fra newbie til ninja på en time
Scala - fra newbie til ninja på en timeScala - fra newbie til ninja på en time
Scala - fra newbie til ninja på en time
karianneberg
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlin
Thijs Suijten
 
About java
About javaAbout java
About java
Jay Xu
 
Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2
Kirill Rozov
 
Kotlin
KotlinKotlin
Miracle of std lib
Miracle of std libMiracle of std lib
Miracle of std lib
Jedsada Tiwongvokul
 
여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language
Ashal aka JOKER
 
Benefits of Kotlin
Benefits of KotlinBenefits of Kotlin
Benefits of Kotlin
Benjamin Waye
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlin
Thijs Suijten
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기
진성 오
 
Scala in a Java 8 World
Scala in a Java 8 WorldScala in a Java 8 World
Scala in a Java 8 World
Daniel Blyth
 
3 kotlin vs. java- what kotlin has that java does not
3  kotlin vs. java- what kotlin has that java does not3  kotlin vs. java- what kotlin has that java does not
3 kotlin vs. java- what kotlin has that java does not
Sergey Bandysik
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 World
BTI360
 
Hey Kotlin, How it works?
Hey Kotlin, How it works?Hey Kotlin, How it works?
Hey Kotlin, How it works?
Chang W. Doh
 
Kotlin, 어떻게 동작하나요
Kotlin, 어떻게 동작하나요Kotlin, 어떻게 동작하나요
Kotlin, 어떻게 동작하나요
Chang W. Doh
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
Aleksandar Prokopec
 
Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015
Iran Entrepreneurship Association
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to Swift
Giordano Scalzo
 

Similar to かとうの Kotlin 講座 こってり版 (20)

Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlin
 
Kotlin killed Java stars
Kotlin killed Java starsKotlin killed Java stars
Kotlin killed Java stars
 
Scala - fra newbie til ninja på en time
Scala - fra newbie til ninja på en timeScala - fra newbie til ninja på en time
Scala - fra newbie til ninja på en time
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlin
 
About java
About javaAbout java
About java
 
Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2
 
Kotlin
KotlinKotlin
Kotlin
 
Miracle of std lib
Miracle of std libMiracle of std lib
Miracle of std lib
 
여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language
 
Benefits of Kotlin
Benefits of KotlinBenefits of Kotlin
Benefits of Kotlin
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlin
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기
 
Scala in a Java 8 World
Scala in a Java 8 WorldScala in a Java 8 World
Scala in a Java 8 World
 
3 kotlin vs. java- what kotlin has that java does not
3  kotlin vs. java- what kotlin has that java does not3  kotlin vs. java- what kotlin has that java does not
3 kotlin vs. java- what kotlin has that java does not
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 World
 
Hey Kotlin, How it works?
Hey Kotlin, How it works?Hey Kotlin, How it works?
Hey Kotlin, How it works?
 
Kotlin, 어떻게 동작하나요
Kotlin, 어떻게 동작하나요Kotlin, 어떻게 동작하나요
Kotlin, 어떻게 동작하나요
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to Swift
 

More from Yutaka Kato

Slack の過去ログ倉庫を建てよう (2017 合宿 LT)
Slack の過去ログ倉庫を建てよう (2017 合宿 LT)Slack の過去ログ倉庫を建てよう (2017 合宿 LT)
Slack の過去ログ倉庫を建てよう (2017 合宿 LT)
Yutaka Kato
 
AOSN読書会 年次活動報告 2017
AOSN読書会 年次活動報告 2017AOSN読書会 年次活動報告 2017
AOSN読書会 年次活動報告 2017
Yutaka Kato
 
Vaadin 8 によるオール java web アプリ開発の仕組みと実践
Vaadin 8 によるオール java web アプリ開発の仕組みと実践Vaadin 8 によるオール java web アプリ開発の仕組みと実践
Vaadin 8 によるオール java web アプリ開発の仕組みと実践
Yutaka Kato
 
Present でスライドを作ろう
Present でスライドを作ろうPresent でスライドを作ろう
Present でスライドを作ろう
Yutaka Kato
 
データで見るAOSN読書会 (2016 合宿 LT)
データで見るAOSN読書会 (2016 合宿 LT)データで見るAOSN読書会 (2016 合宿 LT)
データで見るAOSN読書会 (2016 合宿 LT)
Yutaka Kato
 
GBDC 勉強会 #6 Java イベントレポート 2016
GBDC 勉強会 #6 Java イベントレポート 2016GBDC 勉強会 #6 Java イベントレポート 2016
GBDC 勉強会 #6 Java イベントレポート 2016
Yutaka Kato
 
APDC 勉強会 #4 動的解析 - NASA から学ぶ超高信頼ソフトウェア技術
APDC 勉強会 #4 動的解析 - NASA から学ぶ超高信頼ソフトウェア技術APDC 勉強会 #4 動的解析 - NASA から学ぶ超高信頼ソフトウェア技術
APDC 勉強会 #4 動的解析 - NASA から学ぶ超高信頼ソフトウェア技術
Yutaka Kato
 
GBDC 勉強会 #2 Android Studio 実践レポート
GBDC 勉強会 #2 Android Studio 実践レポートGBDC 勉強会 #2 Android Studio 実践レポート
GBDC 勉強会 #2 Android Studio 実践レポート
Yutaka Kato
 
GBDC 勉強会 #1 Python を用いたツール作成工数の最小化
GBDC 勉強会 #1 Python を用いたツール作成工数の最小化GBDC 勉強会 #1 Python を用いたツール作成工数の最小化
GBDC 勉強会 #1 Python を用いたツール作成工数の最小化
Yutaka Kato
 

More from Yutaka Kato (9)

Slack の過去ログ倉庫を建てよう (2017 合宿 LT)
Slack の過去ログ倉庫を建てよう (2017 合宿 LT)Slack の過去ログ倉庫を建てよう (2017 合宿 LT)
Slack の過去ログ倉庫を建てよう (2017 合宿 LT)
 
AOSN読書会 年次活動報告 2017
AOSN読書会 年次活動報告 2017AOSN読書会 年次活動報告 2017
AOSN読書会 年次活動報告 2017
 
Vaadin 8 によるオール java web アプリ開発の仕組みと実践
Vaadin 8 によるオール java web アプリ開発の仕組みと実践Vaadin 8 によるオール java web アプリ開発の仕組みと実践
Vaadin 8 によるオール java web アプリ開発の仕組みと実践
 
Present でスライドを作ろう
Present でスライドを作ろうPresent でスライドを作ろう
Present でスライドを作ろう
 
データで見るAOSN読書会 (2016 合宿 LT)
データで見るAOSN読書会 (2016 合宿 LT)データで見るAOSN読書会 (2016 合宿 LT)
データで見るAOSN読書会 (2016 合宿 LT)
 
GBDC 勉強会 #6 Java イベントレポート 2016
GBDC 勉強会 #6 Java イベントレポート 2016GBDC 勉強会 #6 Java イベントレポート 2016
GBDC 勉強会 #6 Java イベントレポート 2016
 
APDC 勉強会 #4 動的解析 - NASA から学ぶ超高信頼ソフトウェア技術
APDC 勉強会 #4 動的解析 - NASA から学ぶ超高信頼ソフトウェア技術APDC 勉強会 #4 動的解析 - NASA から学ぶ超高信頼ソフトウェア技術
APDC 勉強会 #4 動的解析 - NASA から学ぶ超高信頼ソフトウェア技術
 
GBDC 勉強会 #2 Android Studio 実践レポート
GBDC 勉強会 #2 Android Studio 実践レポートGBDC 勉強会 #2 Android Studio 実践レポート
GBDC 勉強会 #2 Android Studio 実践レポート
 
GBDC 勉強会 #1 Python を用いたツール作成工数の最小化
GBDC 勉強会 #1 Python を用いたツール作成工数の最小化GBDC 勉強会 #1 Python を用いたツール作成工数の最小化
GBDC 勉強会 #1 Python を用いたツール作成工数の最小化
 

Recently uploaded

Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptxOperational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
sandeepmenon62
 
Refactoring legacy systems using events commands and bubble contexts
Refactoring legacy systems using events commands and bubble contextsRefactoring legacy systems using events commands and bubble contexts
Refactoring legacy systems using events commands and bubble contexts
Michał Kurzeja
 
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
Tier1 app
 
Orca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container OrchestrationOrca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container Orchestration
Pedro J. Molina
 
The Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdfThe Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdf
kalichargn70th171
 
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
kalichargn70th171
 
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
kgyxske
 
Folding Cheat Sheet #6 - sixth in a series
Folding Cheat Sheet #6 - sixth in a seriesFolding Cheat Sheet #6 - sixth in a series
Folding Cheat Sheet #6 - sixth in a series
Philip Schwarz
 
Call Girls Bangalore🔥7023059433🔥Best Profile Escorts in Bangalore Available 24/7
Call Girls Bangalore🔥7023059433🔥Best Profile Escorts in Bangalore Available 24/7Call Girls Bangalore🔥7023059433🔥Best Profile Escorts in Bangalore Available 24/7
Call Girls Bangalore🔥7023059433🔥Best Profile Escorts in Bangalore Available 24/7
manji sharman06
 
TheFutureIsDynamic-BoxLang-CFCamp2024.pdf
TheFutureIsDynamic-BoxLang-CFCamp2024.pdfTheFutureIsDynamic-BoxLang-CFCamp2024.pdf
TheFutureIsDynamic-BoxLang-CFCamp2024.pdf
Ortus Solutions, Corp
 
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Paul Brebner
 
Software Test Automation - A Comprehensive Guide on Automated Testing.pdf
Software Test Automation - A Comprehensive Guide on Automated Testing.pdfSoftware Test Automation - A Comprehensive Guide on Automated Testing.pdf
Software Test Automation - A Comprehensive Guide on Automated Testing.pdf
kalichargn70th171
 
Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...
Paul Brebner
 
Streamlining End-to-End Testing Automation
Streamlining End-to-End Testing AutomationStreamlining End-to-End Testing Automation
Streamlining End-to-End Testing Automation
Anand Bagmar
 
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery FleetStork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
Vince Scalabrino
 
Boost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management AppsBoost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management Apps
Jhone kinadey
 
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid
 
Folding Cheat Sheet #5 - fifth in a series
Folding Cheat Sheet #5 - fifth in a seriesFolding Cheat Sheet #5 - fifth in a series
Folding Cheat Sheet #5 - fifth in a series
Philip Schwarz
 
Microsoft-Power-Platform-Adoption-Planning.pptx
Microsoft-Power-Platform-Adoption-Planning.pptxMicrosoft-Power-Platform-Adoption-Planning.pptx
Microsoft-Power-Platform-Adoption-Planning.pptx
jrodriguezq3110
 

Recently uploaded (20)

Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptxOperational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
 
Refactoring legacy systems using events commands and bubble contexts
Refactoring legacy systems using events commands and bubble contextsRefactoring legacy systems using events commands and bubble contexts
Refactoring legacy systems using events commands and bubble contexts
 
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
 
bgiolcb
bgiolcbbgiolcb
bgiolcb
 
Orca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container OrchestrationOrca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container Orchestration
 
The Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdfThe Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdf
 
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
 
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
 
Folding Cheat Sheet #6 - sixth in a series
Folding Cheat Sheet #6 - sixth in a seriesFolding Cheat Sheet #6 - sixth in a series
Folding Cheat Sheet #6 - sixth in a series
 
Call Girls Bangalore🔥7023059433🔥Best Profile Escorts in Bangalore Available 24/7
Call Girls Bangalore🔥7023059433🔥Best Profile Escorts in Bangalore Available 24/7Call Girls Bangalore🔥7023059433🔥Best Profile Escorts in Bangalore Available 24/7
Call Girls Bangalore🔥7023059433🔥Best Profile Escorts in Bangalore Available 24/7
 
TheFutureIsDynamic-BoxLang-CFCamp2024.pdf
TheFutureIsDynamic-BoxLang-CFCamp2024.pdfTheFutureIsDynamic-BoxLang-CFCamp2024.pdf
TheFutureIsDynamic-BoxLang-CFCamp2024.pdf
 
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
 
Software Test Automation - A Comprehensive Guide on Automated Testing.pdf
Software Test Automation - A Comprehensive Guide on Automated Testing.pdfSoftware Test Automation - A Comprehensive Guide on Automated Testing.pdf
Software Test Automation - A Comprehensive Guide on Automated Testing.pdf
 
Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...
 
Streamlining End-to-End Testing Automation
Streamlining End-to-End Testing AutomationStreamlining End-to-End Testing Automation
Streamlining End-to-End Testing Automation
 
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery FleetStork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
 
Boost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management AppsBoost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management Apps
 
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
 
Folding Cheat Sheet #5 - fifth in a series
Folding Cheat Sheet #5 - fifth in a seriesFolding Cheat Sheet #5 - fifth in a series
Folding Cheat Sheet #5 - fifth in a series
 
Microsoft-Power-Platform-Adoption-Planning.pptx
Microsoft-Power-Platform-Adoption-Planning.pptxMicrosoft-Power-Platform-Adoption-Planning.pptx
Microsoft-Power-Platform-Adoption-Planning.pptx
 

かとうの Kotlin 講座 こってり版

  • 2. 
 😁 package demo class Person(val name: String, val age: Int? = null) { override fun toString(): String { return "name=$name, age=$age" } } fun main(args: Array<String>) { val persons = listOf(Person(" "), Person(" ", age = 30)) val oldest = persons.maxBy { it.age ?: 0 } println(" $oldest") } // name= , age=30 package demo; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Optional; public final class Person { private String name; private Integer age = null; public Person(String name) { this.name = name; } public Person(String name, Integer age) { this.name = name; this.age = age; } @Override public String toString() { return "name=" + name + ", age=" + age; } public static void main(String[] args) { List<Person> persons = Arrays.asList( new Person(" "), new Person(" ", 30)); Optional<Person> oldest = persons.stream() .max(Comparator.comparing(p -> p.age == null ? 0 : p.age)); System.out.println(" " + oldest.orElse(null)); } // name= , age=30 }
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14. if while for 
 
 import java.util.Random fun main(args: Array<String>) { // val rand = Random() val a = rand.nextBoolean() val b = rand.nextBoolean() // if (a == b) { println("A B ") } else { println("A B ") } // while (rand.nextBoolean() != a) { print(" ") } println(" !") } // ( ) // A B // ! // 2 println(if (a == b) "A B " else "A B ") for (i in listOf("a", "b", "c")) { println(i) } for (s in listOf("a", "b", "c").withIndex()) { println(s.index) println(s.value) }
  • 15. 
 default else import java.util.Random fun main(args: Array<String>) { // when 1 when (Random().nextBoolean()) { true -> println(" ") false -> println(" ") } // when 2 println(when (Random().nextBoolean()) { true -> " " false -> " " }) // when val num = Random().nextInt() when { num > 0 -> println("0 ") num < 0 -> println("0 ") else -> println(" !") } }
  • 16. fun ( : , …) { } fun ( : , …): { } // fun max(a: Int, b: Int): Int = if (a > b) a else b // fun min(a: Int, b: Int): Int { return if (a > b) b else a }
  • 17. val var // val question = " " // val answer: Int = 42 // var foo = "foo" fun update() { foo = "bar" // }
  • 18. Byte, Short, Int, Long,
 Float, Double, Char, Boolean String Object Void Any, Unit, Nothing // val ints: Set<Int> = setOf(100, -1, 1_000_000) val longs: Set<Long> = setOf(100L, -1L) val doubles: Set<Double> = setOf(0.12, 2.0, 1.2e10, 1.2e-10) val floats: Set<Float> = setOf(123.4f, .456F, 1e3f) val chars: Set<Char> = setOf('a', 't', 'u0009') val hexValues: Set<Long> = setOf(0xCAFEBABE, 0xbcdL) val binValues: Set<Long> = setOf(0B0, 0b000000101) val booleans: Set<Boolean> = setOf(true, false)
  • 19. $value ${statement} fun main(args: Array<String>) { val name = if (args.isNotEmpty()) args[0] else "Kotlin" println("Hello, $name!") println("Hello, ${name.toUpperCase()}!") val rawString = """ <html> <body> Hello, $name </body> </html> """.trimIndent() println(rawString) } // Hello, Kotlin! // Hello, KOTLIN! // <html> // <body> // Hello, Kotlin // </body> // </html> trimIndent()
  • 20. Type? Type null NullPointerException 
 fun main(args: Array<String>) { val x: String? = null // val y: String = x // ! val len = if (x != null) x.length else 0 // : if-then x null println(len) // 0 }
  • 21. fun ops() { var n = 1 - 1 * 1 / 1 % 1 // (plus, minus, times, div, mod) n += 1 // (plusAssign) -n++ // (unaryMinus, inc) val b = n == 1 // (equals) val m = mapOf("one" to 1, "two" to 2) val e = m["one"] // (index) val i = "two" in m // in (contains) val l = 1..100 // (rangeTo) } fun mustPerson(a: Any): Person { return a as Person // as - ClassCastException } fun mayPerson(a: Any) { val p: Person? = a as? Person // as? - null val pMsg: String? = p?.toString() // ?. - (null + ) println(pMsg ?: " ") // ?: - (null ) } Int shl, shr, ushr, and, or, xor, inv
  • 22. operator infix class Point3D(val x: Int, val y: Int, val z: Int) open class Point2D(val x: Int, val y: Int) { // + operator fun plus(other: Point2D): Point2D { return Point2D(x + other.x, y + other.y) } // infix infix fun addZ(z: Int): Point3D { return Point3D(x, y, z) } } fun main(args: Array<String>) { val p1 = Point2D(5, 10) val p2 = p1 + Point2D(2, 2) val p3 = p2 addZ 1 // , p2.addZ(1) println("${p3.x}, ${p3.y}, ${p3.z}") // 7, 12, 1 }
  • 24. val itemNullable: Set<Int?> = setOf(1, 2, null) // null val listNullable: Set<Int>? = null // null val bothNullable: Set<Int?>? = setOf(1, 2, null) // null
  • 25. init 
 
 
 super() {} // , Java public final class User1 {} class User1 // ( ) class User2(val nickname: String) // class User3(_nickname: String) { val nickname = _nickname } // constructor class User4 private constructor(_nickname: String) { val nickname = _nickname } // ( ) class User5 { constructor(nickname: String) { println(nickname) } constructor(nickname: String, enabled: Boolean) { println("$nickname (enabled=$enabled)") } } class User1 { init { println(" ") } }
  • 26. open, final, abstract, override final final open final public, internal, protected, private public internal
  • 27. class Person( val name: String, // , getter private val age: Int, // , getter var isMarried: Boolean // , getter, setter ) class Rectangle(val height: Int, val width: Int) { val isSquare: Boolean get() { // getter return height == width } }
  • 28. equals hashCode toString data class User(val id: Long, val name: String, private val address: List<String>) fun main(args: Array<String>) { val user = User(1L, " ", listOf(" ", " ")) if (user.id != 1L) throw InternalError() println(user) } // User(id=1, name= , address=[ , ])
  • 29. interface : InterfaceName interface Clickable { fun click() // fun showOff() = println(" !") // } class Button : Clickable { override fun click() = println(" ") }
  • 30. abstract fun abstract class open SubClass : SuperClass()
 abstract class Animated { // override abstract fun animate() // override open fun stopAnimating() { } // override fun animateTwice() { } } class AnimatedImpl : Animated() { override fun animate() { println("animating") } override fun stopAnimating() { println("override") } }
  • 31. 
 by interface Base { fun print() } class BaseImpl(val x: Int) : Base { override fun print() = print(x) } class Derived(b: Base) : Base by b // Derived Base fun main(args: Array<String>) { val b = BaseImpl(10) Derived(b).print() // 10 }
  • 32. // ( + ) object Payroll { val allEmployees = arrayListOf<Person>() fun calculateSalary() { // ... } } fun main(args: Array<String>) { val window = JWindow() window.addMouseListener( // (Java ) object : MouseAdapter() { override fun mouseClicked(e: MouseEvent) { println(" !") } override fun mouseEntered(e: MouseEvent) { println(" !") } } ) }
  • 33. 
 
 serialVersionUID Companion class A { companion object { const val foo = "hoge" fun bar() { println(" ") } } } fun main(args: Array<String>) { println(A.foo) A.bar() } // Java public class Main { public static void main(String[] args) { System.out.println(A.foo); A.Companion.bar(); } } companion object Loader { fun fromJSON(json: String): Person = … }
  • 34. 
 
 IOException Closable use close 
 // try-catch-finally fun readNumber(reader: BufferedReader): Int? { val number = try { Integer.parseInt(reader.readLine()) } catch (e: NumberFormatException) { null } finally { reader.close() } return number } // use { try-catch } (Java try-with-resources ) fun readNumber2(reader: BufferedReader): Int? { return reader.use { try { Integer.parseInt(it.readLine()) } catch (e: NumberFormatException) { null } } }
  • 35. import javax.swing.JButton; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; // Java public class Lambda { public static void main(String[] args) { JButton button = new JButton(); // button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("Action performed"); } }); // button.addActionListener(e -> System.out.println("Action performed")); } } import javax.swing.JButton fun main(args: Array<String>) { val button = JButton() button.addActionListener { e -> println("Action performed") } }
  • 36. 
 it data class Person(val name: String, val age: Int) fun findTheOldest(people: List<Person>): Person? { var maxAge = 0 var theOldest: Person? = null for (person in people) { if (person.age > maxAge) { maxAge = person.age theOldest = person } } return theOldest } fun main(args: Array<String>) { val people = listOf(Person("Alice", 29), Person("Bob", 31)) println(findTheOldest(people)) // println(people.maxBy { person -> person.age }) // println(people.maxBy { it.age }) // (it ) } val sum = { x: Int, y: Int -> x + y }
  • 37. Iterable fun twoAndThree(operation: (Int, Int) -> Int) { // val result = operation(2, 3) // println(" $result") } fun main(args: Array<String>) { twoAndThree { a, b -> a + b } // 5 twoAndThree { a, b -> a * b } // 6 }
  • 38. let, with, run, apply, also this apply, with, run it also, let fun main(args: Array<String>) { val person = Person() // person.name = " " person.setDateOfBirth(1988, 4, 12) val person2 = Person().apply { // apply name = " " setDateOfBirth(1988, 4, 12) } val person3 = Person().also { // also it.name = " " it.setDateOfBirth(1988, 4, 12) } val person4 = with(Person()) { // with name = " " setDateOfBirth(1988, 4, 12) } person.name?.let { println(it) } // name null let person.name?.run { println(this) } // name null run }
  • 39. import 
 BigDecimal import java.io.PrintWriter import java.io.StringWriter fun Exception.stackTraceString(): String { val sw = StringWriter() PrintWriter(sw).use { printStackTrace(it) } return sw.toString() } fun main(args: Array<String>) { println(RuntimeException().stackTraceString()) }
  • 40.