applyの説明
class Human(val name: String, val age: Int) { } object Human { def apply(name: String, age:Int) = { new Human(name, age) } }
としておくと、以下のようにインスタンスを生成できる。
val h = Human("taro", 20)
コンパニオンオブジェクトのapplyがファクトリメソッドとして使われるので、newと書かなくてもインスタンスを生成できる。
unapplyの説明
class Human(val name: String, val age: Int) { } object Human { def unapply(h: Human): Option[(String, Int)] = Some((h.name, h.age)) }
としておくと、以下のようにパターンマッチで使える。
val h = new Human("taro", 20) h match { case Human(name, age) => println(s"name=$name, age=$age") case _ => println("unknown") }
ケースクラス
case classを使ってあんなことやこんなことができるのは、実はapply、unapplyが自動生成されていたかららしい。case class Human(name: String, age: Int) { } val h = Human("taro", 20) h match { case Human(name, age) => println(s"name=$name, age=$age") case _ => println("unknown") }
The actual time and effort took to create this wonderful article were really great and would like to read this blog regularly to get more updates...
返信削除Apache Spark Training | Spark Online Training
Thank you for sharing wonderful information with us to get some idea about that content. check it once through
返信削除Machine Learning With TensorFlow Training and Course in Tel Aviv
| CPHQ Online Training in Beirut. Get Certified Online
nice post...
返信削除internship report on python
free internship in chennai for ece students
free internship for bca
internship for computer science engineering students in india
internships in hyderabad for cse students 2018
electrical companies in hyderabad for internship
internships in chennai for cse students 2019
internships for ece students
inplant training in tcs chennai
internship at chennai