Introduction to Scala Part3: Option & Pattern Matching
Bubu
2,990 views
Create your own Option type
- Some extends Option
- None is an object that extends Option
Goal of this exercice: create your own MyOption, MySome and MyNone. For the sake of simplicity, MyOption, MySome and MyNone will have simpler implementations
MySome
MyNone
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Suggested playgrounds
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package fp101.tp03.option
object ExerciceOptionCreator {
/**
*
* Our own simplified implementation of Option type
*
*
*/
trait MyOption[+T] {
def get: T
/**
*
* Method to implement here
*
* Note: U :> T says that B type parameter must be a supertype of T
* hint: implements the methods of MySome and MyNone before
*/
def getOrElse[U >: T](e: U): U = ???
def isEmpty: Boolean
}
class MySome[T](x: T) extends MyOption[T] {
def get: T = ???
def isEmpty: Boolean = ???
}
object MySome {
def apply[T](e: T): MySome[T] = ???
}
object MyNone extends MyOption[Nothing] {
def get = ???
def isEmpty: Boolean = ???
}
}