import java.time.LocalDate
import java.time.chrono.ChronoLocalDate
fun format(userName: String, domain: String) = "$userName@$domain"
fun findMinMax(list: List<Int>): Pair<Int, Int> {
// do the math
return Pair(50, 100)
}
data class User(val username: String, val email: String) // 1
fun getUser() = User("Mary", "[email protected]")
class Pair<K, V>(val first: K, val second: V) { // 1
operator fun component1(): K {
return first
}
operator fun component2(): V {
return second
}
}
fun main() {
val date: ChronoLocalDate? = LocalDate.now() // 1
if (date != null) {
println(date.isLeapYear) // 2
}
if (date != null && date.isLeapYear) { // 3
println("It's a leap year!")
}
if (date == null || !date.isLeapYear) { // 4
println("There's no Feb 29 this year...")
}
if (date is LocalDate) {
val month = date.monthValue // 5
println(month)
}
val (num, name) = Pair(1, "one") // 2
println("num = $num, name = $name")
val user = getUser()
val (username, email) = user // 2
println(username == user.component1()) // 3
val (_, emailAddress) = getUser() // 4
val (x, y, z) = arrayOf(5, 10, 15) // 1
val map = mapOf("Alice" to 21, "Bob" to 25)
for ((name, age) in map) { // 2
println("$name is $age years old")
}
val (min, max) = findMinMax(listOf(100, 90, 50, 98, 76, 83)) // 3
val greeting = "Kotliner"
println("Hello $greeting") // 1
println("Hello ${greeting.uppercase()}") // 2
println(format("mario", "example.com")) // 1
println(format("domain.com", "username")) // 2
println(format(userName = "foo", domain = "bar.com")) // 3
println(format(domain = "frog.com", userName = "pepe")) // 4
}
Kotlin提升生产力
猜你喜欢
转载自blog.csdn.net/zhuziying99/article/details/132201153
今日推荐
周排行