SlideShare une entreprise Scribd logo
1  sur  41
Télécharger pour lire hors ligne
😎




😁
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 講座 こってり版

Contenu connexe

Tendances

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 zipperosfameron
 
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 ElixirPaweł 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 editionosfameron
 
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 examplesNebojša Vukšić
 
Kotlin from-scratch 2 - functions
Kotlin from-scratch 2 - functionsKotlin from-scratch 2 - functions
Kotlin from-scratch 2 - functionsFranco Lombardo
 
Probabilistic Programming in Scala
Probabilistic Programming in ScalaProbabilistic Programming in Scala
Probabilistic Programming in ScalaBeScala
 
Groovy puzzlers jug-moscow-part 2
Groovy puzzlers jug-moscow-part 2Groovy puzzlers jug-moscow-part 2
Groovy puzzlers jug-moscow-part 2Evgeny Borisov
 
Inteligencia artificial 4
Inteligencia artificial 4Inteligencia artificial 4
Inteligencia artificial 4Nauber Gois
 
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 88Mahmoud Samir Fayed
 
Exhibition of Atrocity
Exhibition of AtrocityExhibition of Atrocity
Exhibition of AtrocityMichael 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 184Mahmoud 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 TwenteDirkjan Bussink
 
Elixir & Phoenix – fast, concurrent and explicit
Elixir & Phoenix – fast, concurrent and explicitElixir & Phoenix – fast, concurrent and explicit
Elixir & Phoenix – fast, concurrent and explicitTobias Pfeiffer
 
Elixir & Phoenix – fast, concurrent and explicit
Elixir & Phoenix – fast, concurrent and explicitElixir & Phoenix – fast, concurrent and explicit
Elixir & Phoenix – fast, concurrent and explicitTobias Pfeiffer
 

Tendances (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
 

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

Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlinintelliyole
 
Kotlin killed Java stars
Kotlin killed Java starsKotlin killed Java stars
Kotlin killed Java starsMatteo 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 timekarianneberg
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlinThijs Suijten
 
About java
About javaAbout java
About javaJay 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 2Kirill Rozov
 
여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala LanguageAshal aka JOKER
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlinThijs 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 WorldDaniel 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 notSergey 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 WorldBTI360
 
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
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to SwiftGiordano Scalzo
 

Similaire à かとうの 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
 

Plus de Yutaka Kato

Slack の過去ログ倉庫を建てよう (2017 合宿 LT)
Slack の過去ログ倉庫を建てよう (2017 合宿 LT)Slack の過去ログ倉庫を建てよう (2017 合宿 LT)
Slack の過去ログ倉庫を建てよう (2017 合宿 LT)Yutaka Kato
 
AOSN読書会 年次活動報告 2017
AOSN読書会 年次活動報告 2017AOSN読書会 年次活動報告 2017
AOSN読書会 年次活動報告 2017Yutaka 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 イベントレポート 2016Yutaka 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
 

Plus de 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 を用いたツール作成工数の最小化
 

Dernier

CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 

Dernier (20)

CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 

かとうの 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.