class className <generic data type> (properties...)
val instanceName = class<generic data type>(parameters)
예시
class Question<T>(
val questionText: String,
val answer: T,
val difficulty: String
)
fun main() {
val question1 = Question<String>("Quoth the raven ___", "nevermore", "medium")
val question2 = Question<Boolean>("The sky is green. True or false", false, "easy")
val question3 = Question<Int>("How many days are there between full moons?", 28, "hard")
}
가능한 값 집합이 제한되어 있는 유형
언제 필요한가? -- 만약 위의 예시의 difficulty가 easy
, medium
, hard
로 정의되어 있다면,
형태
enum class className(
CASE1,
CASE2
)
,
로 구분하고, 상수 이름을 모두 대문자
로 표기한다.
className.caseName
: .
연산자를 사용하여 참조한다.
예시
enum class Difficulty {
EASY, MEDIUM, HARD
}
class Question<T>(
val questionText: String,
val answer: T,
val difficulty: Difficulty
)
val question1 = Question<String>("Quoth the raven ___", "nevermore", Difficulty.MEDIUM)
val question2 = Question<Boolean>("The sky is green. True or false", false, Difficulty.EASY)
val question3 = Question<Int>("How many days are there between full moons?", 28, Difficulty.HARD)
data class className()
object objectName {}
objectName.propertyName : `.` 연산자를 사용하여 참조한다.
object StudentProgress {
var total: Int = 10
var answered: Int = 3
}
fun main() {
...
println("${StudentProgress.answered} of ${StudentProgress.total} answered.")
}
예시
16.dp
해당 데이터 유형의 일부인 것처럼 .
으로 액세스할 수 있는 속성과 메서드를 추가한다.
형태
val typeName.propertyName: dataType
property getter
fun typeName.functionName(parameters): returnType { }
예시
class Quiz {
val question1 = Question<String>("Quoth the raven ___", "nevermore", Difficulty.MEDIUM)
val question2 = Question<Boolean>("The sky is green. True or false", false, Difficulty.EASY)
val question3 = Question<Int>("How many days are there between full moons?", 28, Difficulty.HARD)
companion object StudentProgress {
var total: Int = 10
var answered: Int = 3
}
}
val Quiz.StudentProgress.progressText: String
get() = "${answered} of ${total} answered"
fun main() {
println(Quiz.progressText)
}
to access class properties and methods
fun printQuiz() {
question1.let {
println(it.questionText)
println(it.answer)
println(it.difficulty)
}
}
Quiz().apply {
printQuiz()
}