Daily Kotlin - 동기화, inline 함수, 익명함수, 확장 함수, 중위함수, if, when-in, for, inlineLambda return
- 공유 자원 보호
package chap03.section4
import java.util.concurrent.locks.ReentrantLock
var sharable = 1
fun main() {
val reLock = ReentrantLock()
//공유자원 접근 보호
lock(reLock, ::criticalFunc)
println(sharable)
}
fun criticalFunc() {
sharable += 1
}
fun <T> lock(reLock: ReentrantLock, body: () -> T): T {
reLock.lock()
try {
return body()
} finally {
reLock.unlock()
}
}
- inline function
package chap03.section5
fun main() {
shortFunc(3) {println("First call: $it")}
shortFunc(5) {println("Second call: $it")}
}
inline fun shortFunc(a: Int, out: (Int) -> Unit) {
println("Before calling out()")
out(a)
println("After calling out()")
}
Before calling out()
First call: 3
After calling out()
Before calling out()
Second call: 5
After calling out()
- 익명 함수 리턴
package chap03.section5.localreturn
fun main() {
shortFunc(3) {
println("First call: $it")
return
}
}
inline fun shortFunc(a: Int, out: (Int) -> Unit) {
println("Before calling out()")
out(a)
println("After calling out()")
}
Before calling out()
First call: 3
- 확장 함수
package chap03.section5
fun main() {
val source = "Hello World!"
val target = "Kotlin"
println(source.getLongString(target))
}
fun String.getLongString(target: String): String = if(this.length > target.length) this else target
- 중위 함수
package chap03.section5
fun main() {
val multi = 3 multiply 10
println("multi: $multi")
}
infix fun Int.multiply(x: Int): Int = this * x
- if
package chap04.section1
fun main() {
val a = 12
val b = 7
val max = if(a > b) {
println("a 선택")
a
} else {
println("b 선택")
b
}
println(max)
}
- else if
package chap04.section1
fun main() {
print("Enter the score: ")
val score = readLine()!!.toDouble()
var grade: Char = 'F'
if (score >= 90.0) {
grade = 'A'
} else if(score >= 80.0) {
grade = 'B'
} else if(score >= 70.0) {
grade = 'C'
}
println("Score: $score Grade: $grade")
}
- when, in
package chap04.section1
fun main() {
print("Enter the score: ")
val score = readLine()!!.toDouble()
var grade: Char = 'F'
when(score) {
in 90.0..100.0 -> grade = 'A'
in 80.0..89.9 -> grade = 'B'
in 70.0..79.9 -> grade = 'C'
!in 70.0..100.0 -> grade = 'F'
}
println("score: $score grade : $grade")
}
Enter the score: 94
score: 94.0 grade : A
- for
while이랑 do-while은 일반적인 JAVA와 동일
package chap04.section2
fun main() {
print("Enter the lines: ")
val n = readLine()!!.toInt()
for (line in 1..n) {
for (space in 1..(n-line)) print(" ")
for (star in 1..(2*line-1)) print("*")
println()
}
}
- inlineLambda return
package chap04.section3
fun main() {
retFunc()
}
inline fun inlineLambda(a: Int, b: Int, out: (Int, Int) -> Unit) {
out(a, b)
}
fun retFunc() {
println("start of retFunc")
inlineLambda(13, 3) { a, b ->
val result = a + b
if(result > 10) return
println("result : $result")
}
println("end of retFunc")
}
start of retFunc
Comments