var nullName: String? = null
(1) ?. 연산자
var nullName: String? = null
val upperCaseName: String? = nullName?.toUpperCase()
print(upperCaseName)
null
(2) ?: 연산자
var name = "Minha"
var lastName: String? = null
val fullName = name + " " + (lastName?: "No lastName")
print(fullName)
Minha No lastName
fun nonNull(str: String?) {
var notNullName: String = str!!
val upperCaseName = notNullName.toUpperCase()
print(upperCaseName)
}
// str이 minha일 때
MINHA
(1) let 함수
(2) let 함수와 ?.
val name: String? = "Minha Lee"
name?.let{
println("My name is ${name}")
}
My name is Minha Lee
class Human {
val name = "minha"
fun running() {
println("Running is so tired")
}
}
fun main() {
val human = Human()
human.running()
println("This human's name is ${human.name}")
}
Running is so tired
This human's name is minha
// 방법1. 기본 생성자
class Human constructor(name: String) {
val name = name
fun running() {
println("Running is so tired")
}
}
// 방법2. 클래스의 프로퍼티명과 생성자의 프로퍼티명이 같다면
// 생성자의 프로퍼티에 val을 붙이면 그 자체로 클래스의 프로퍼티가 됨
// constructor 키워드도 생략 가능
class Human (val name: String) {
fun running() {
println("Running is so tired")
}
}
fun main() {
val human = Human("seungjae")
human.running()
println("This human's name is ${human.name}")
}
Running is so tired
This human's name is seungjae
class Human (val name: String = "Anonymous") {
init {
println("I am new human")
}
fun running() {
println("Running is so tired")
}
}
fun main() {
val human = Human()
human.running()
println("This human's name is ${human.name}")
}
I am new human
Running is so tired
This human's name is Anonymous
(1) 부생성자
class Human (val name: String = "Anonymous") {
constructor(name: String, age: Int) : this(name) {
println("my name is ${name}, ${age} years old")
}
init {
println("I am new human")
}
fun running() {
println("Running is so tired")
}
}
fun main() {
val human = Human("seungjae", 25)
human.running()
}
I am new human
my name is seungjae, 25 years old
Running is so tired
open class Human (val name: String = "Anonymous") {
init {
println("I am new human")
}
open fun running() {
println("Running is so tired")
}
}
class Korean: Human("seungjae") {
override fun running() {
super.running()
println("아 힘들다")
}
}
fun main() {
val korean = Korean()
korean.running()
println("my name is ${human.name}")
}
I am new human
Running is so tired
아 힘들다
my name is seungjae