๋ฐ์ํ
1. Lamda
: ๋๋ค์์ ์ต๋ช ํจ์ -> value์ฒ๋ผ ๋ค๋ฃฐ ์ ์์.
1) ๋ฉ์๋์ ํ๋ผ๋ฏธํฐ๋ก ๋๊ฒจ์ค ์ ์์. fun maxBy(a: Int)
2) return ๊ฐ์ผ๋ก ์ฌ์ฉ ๊ฐ๋ฅ.
1-1. ๋๋ค์ ๊ธฐ๋ณธ์ ์
val lamdaName : Type = {argumentList -> codeBody}
val square : (Int) -> (Int) = {number -> number*number}
val nameAge = {name : String, age : Int ->
"my name is ${name}, I'm ${age}"
}
fun main(){
println(square(12))
println(nameAge("whkakrkr", 21))
}
1-2. ๋๋ค์ ํ์ฅํจ์
val pizzaIsGreat : String.() -> String = {
this + "Pizza is the best!"
}
fun extendString(name:String, age:Int) : String {
val introduceMyself : String.(Int) -> String = {"I am ${this} and ${it} years old."}
return name.introduceMyself(age)
}
1-3. ๋๋ค์ ๋ฆฌํด
val calculateGrade : (Int) -> String = {
when(it){
in 0..40 -> "fail"
in 41..70 -> "pass"
in 71..100 -> "perfect"
else -> "huh?"
}
}
1-4. ๋๋ค๋ฅผ ํํํ๋ ์ฌ๋ฌ๊ฐ์ง ๋ฐฉ๋ฒ
fun invokeLamda(lamda : (Double) -> Boolean) : Boolean {
return lamda(5.2343)
}
fun main(){
val lamda = {number : Double ->
number == 4.3213
}
println(invokeLamda(lamda))
println(invokeLamda({it > 3.22}))
println(invokeLamda { it > 3.22 })
}
๋ฒํผ์ ๋๋ค์ ์ฌ์ฉ
1 ) kotlin ์ธํฐํ์ด์ค๊ฐ ์๋ ์๋ฐ ์ธํฐํ์ด์ค
2 ) ๊ทธ ์ธํฐํ์ด์ค๋ ๋ฑ ํ๋์ ๋ฉ์๋๋ง ๊ฐ์ ธ์ผํจ
2. Data Class
data class Ticket(val companyName :String, val name :String, var date :String, var seatNumber :Int)
class TicketNormal(val companyName :String, val name :String, var date :String, var seatNumber :Int)
// toString(), hashCode(), equals(), copy()
fun main() {
val ticketA = Ticket( "KoreanAir", "whk", "2001-06-13",13)
val ticketB = TicketNormal( "KoreanAir", "whk", "2001-06-13",13)
println(ticketA) //Ticket(companyName=KoreanAir, name=whk, date=2001-06-13, seatNumber=13)
println(ticketB) //com.example.practice_codewithjoyce.TicketNormal@61bbe9ba
}
3. Companion object
class Book private constructor(val id : Int, val name : String) {
companion object BookFactory : IdProvider {
override fun getId() : Int {
retrurn 444
}
val myBook = "new book"
fun create() = Book( 0, myBook
}
}
interface IdProvider {
fun getId() : Int
}
fun main(){
val book = Book.Companion.create()
val bookId = Book.BookFactory.getId()
println("${book.id} ${book.name}")
}
4. Object
//Singleton Pattern
object CarFactory {
val cars = mutableListOf<Car>()
fun makeCar(horsePower : Int) : Car {
val car = Car(horsePower)
cars.add(car)
return car
}
}
data class Car(val horsePower : Int)
fun main() {
val car : Car = CarFactory.makeCar(10)
val car2 : Car = CarFactory.makeCar(200)
println(car)
println(car2)
println(CarFactory.cars.size.toString())
}
๋ฐ์ํ
'๐ฆ Chango > ๐ฃ EDOC' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Android Studio / Kotlin] ์ฝํ๋ฆฐ๊ณผ ๋ฆฌ์คํธ๋ทฐ (List View) (0) | 2021.05.02 |
---|---|
[Android Studio / Kotlin] ์ค์ ์ฑ๊ฐ๋ฐ์์ ์ฌ์ฉํ ์ฝํ๋ฆฐ๋ง ๋ชจ์๋ณด๊ธฐ (๊ธฐ๋ณธ) (0) | 2021.05.02 |
[AndroidStudio / Kotlin] Unresolved reference ์ค๋ฅ ํด๊ฒฐ (0) | 2021.05.01 |
[AndroidStudio / Kotlin] ์ฝํ๋ฆฐ ๊ธฐ๋ณธ๋ฌธ๋ฒ (0) | 2021.04.30 |
[CSS] Flexbox Froggy ํ๋ฉด์ CSS flexbox ๊ณต๋ถํ๊ธฐ (0) | 2021.04.29 |