12. DBFluteフェス 2018
■ if-else, try-catch
➔Javaのようにも書けるが...
文法: if, try
12
var max: Int
if (a > b) {
max = a
} else {
max = b
}
try {
readFile()
return true
} catch (e: IOException) {
e.printStackTrace()
return false
}
28. DBFluteフェス 2018
■ データを保持するためのクラス
➔コンストラクタ等を書く必要がない
■ equals() , hashCode(), toString()などを自動的に
生成してくれる
➔copy(), componentN()なども
Data Class
28
data class User(val name: String, val email: String)
val taro = User(name = "Taro", age = 18)
29. DBFluteフェス 2018
■ Javaと同じくジェネリクスをサポート
■ Javaとの違い
➔変性(<? extends T>的な)はinとoutで書ける
Generics
29
interface Source<out T> {
fun nextT(): T
}
fun demo(strs: Source<String>) {
val objects: Source<Any> = strs
}
class Box<T>(t: T) {
var item = t
}
val box: Box<Int> = Box<Int>(1)
30. DBFluteフェス 2018
■ ラムダ式は{}で囲む
■ ラムダ式の中からアクセスできる
➔Javaと違い、値の変更も可
ラムダ式
30
val sum = {x: Int, y: Int -> x + y} // sumの型は "(Int, Int) -> Int"
println(sum(1,2)) // sum.invoke(1,2) でもOK
var sum = 0
val ints = arrayOf(1, 2, 3)
ints.filter { it > 0 }.forEach { sum += it } // ラムダ式の外側の()は省略可
println(sum)
45. DBFluteフェス 2018
■ 書き方は大きくは変わらない
実行メソッド
45
@Execute
fun index(): HtmlResponse {
val recentProducts = mappingToProducts(selectRecentProductList())
val highPriceProducts = mappingToProducts(selectHighPriceProductList())
return asHtml(ParadeplazaHtmlPath.path_Mypage_MypageHtml)
.renderWith { data ->
data.register("recentProducts", recentProducts)
data.register("highPriceProducts", highPriceProducts)
}
}
46. DBFluteフェス 2018
■ Nullableなvarになる
Formクラス
46
class MemberAddForm {
@Required
var memberName: String? = null
@Required
var memberAccount: String? = null
@ValidateTypeFailure // using calendar so basically unneeded but just in case
var birthdate: LocalDate? = null
@Required
var memberStatus: CDef.MemberStatus? = null
}
47. DBFluteフェス 2018
■ 普通にBhvを使える
➔dataクラスにするいいことがあるか(?)
DBFlute関連
47
private fun insertMember(form: MemberAddForm) {
val member = Member()
member.memberName = form.memberName
member.memberAccount = form.memberAccount
member.birthdate = form.birthdate
member.memberStatusCodeAsMemberStatus = form.memberStatus
if (member.isMemberStatusCodeFormalized) {
member.formalizedDatetime = timeManager.currentDateTime()
}
memberBhv.insert(member)
}