Skip to content

Commit d416031

Browse files
authored
Extractor Objects (#48)
1 parent 5bb2ae6 commit d416031

File tree

1 file changed

+26
-0
lines changed
  • core-scala/src/main/scala/com/baeldung/scala

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package com.baeldung.scala
2+
3+
class User(val name: String, val age: Int)
4+
5+
object User {
6+
def apply(name: String, age: Int) = new User(name, age)
7+
8+
def apply(name: String) = new User(name, 0)
9+
10+
def unapply(u: User): Option[(String, Int)] = Some(u.name, u.age)
11+
}
12+
13+
object UserMainApp extends App {
14+
val user1: User = new User("John", 25)
15+
val user2: User = User.apply("John", 25)
16+
val user3: User = User("John", 25)
17+
18+
val userArgs: Option[(String, Int)] = User.unapply(user1)
19+
20+
user1 match {
21+
case User(_, age) if age < 18 =>
22+
println("You are not allowed to get a driver license.")
23+
case User(_, age) if age >= 18 =>
24+
println("You are allowed to get a driver's license.")
25+
}
26+
}

0 commit comments

Comments
 (0)