Kotlin-data-classes

提供:Dev Guides
移動先:案内検索

Kotlin-データクラス

この章では、Kotlinプログラミング言語のデータクラスについて詳しく学習します。 クラスは、「データ」としてマークされるたびに、データクラスとしてマークできます。 このタイプのクラスは、基本データを区別するために使用できます。 これ以外には、他の機能は提供されません。

すべてのデータクラスには1つのプライマリコンストラクターが必要であり、すべてのプライマリコンストラクターには少なくとも1つのパラメーターが必要です。 クラスがデータとしてマークされるたびに、「toString()」、「hashCode()」など、そのデータクラスの組み込み関数の一部を使用できます。 データクラスには、abstract and openまたはinternalのような修飾子を含めることはできません。 データクラスは他のクラスにも拡張できます。 次の例では、1つのデータクラスを作成します。

fun main(args: Array<String>) {
   val book: Book = Book("Kotlin", "TutorialPoint.com", 5)
   println("Name of the Book is--"+book.name)//"Kotlin"
   println("Puclisher Name--"+book.publisher)//"TutorialPoint.com"
   println("Review of the book is--"+book.reviewScore)//5
   book.reviewScore = 7
   println("Printing all the info all together--"+book.toString())
  //using inbuilt function of the data class

   println("Example of the hashCode function--"+book.hashCode())
}

data class Book(val name: String, val publisher: String, var reviewScore: Int)

上記のコードは、一部のデータを保持するために1つのデータクラスを作成し、メイン関数からそのすべてのデータメンバーにアクセスしたブラウザーで、次の出力を生成します。

Name of the Book is--"Kotlin"
Puclisher Name--"TutorialPoint.com"
Review of the book is--5
Printing all the info all together--(name-Kotlin, publisher-TutorialPoint.com, reviewScore-7)
Example of the hashCode function---1753517245