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
}
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
}