Class: J8::Optional
Class Method Summary
collapse
Instance Method Summary
collapse
Methods included from Common
callable_from_proc, from_callable, from_callable_class, initialize, lambda?, make_lambda, raise_unless_lambda
Constructor Details
#initialize(value = nil) ⇒ Optional
Returns a new instance of Optional.
7
8
9
|
# File 'lib/j8/optional.rb', line 7
def initialize(value = nil)
@value = value
end
|
Class Method Details
11
12
13
|
# File 'lib/j8/optional.rb', line 11
def self.empty
J8::Optional.new
end
|
.of_nilable(value) ⇒ Object
21
22
23
|
# File 'lib/j8/optional.rb', line 21
def self.of_nilable(value)
J8::Optional.new(value)
end
|
Instance Method Details
#empty? ⇒ Boolean
25
26
27
|
# File 'lib/j8/optional.rb', line 25
def empty?
@value.nil?
end
|
#equals?(object) ⇒ Boolean
Also known as:
==
29
30
31
|
# File 'lib/j8/optional.rb', line 29
def equals?(object)
@value == object
end
|
#filter(predicate = nil, &block) ⇒ Object
34
35
36
37
38
39
40
41
42
|
# File 'lib/j8/optional.rb', line 34
def filter(predicate = nil, &block)
callable = from_callable_class(predicate, block, J8::Predicate)
if present? && callable.test(@value)
J8::Optional.new(@value)
else
J8::Optional.empty
end
end
|
#flat_map(function = nil, &block) ⇒ Object
44
45
46
47
48
49
50
51
|
# File 'lib/j8/optional.rb', line 44
def flat_map(function = nil, &block)
callable = from_callable_class(function, block, J8::Function)
return J8::Optional.empty unless present?
callable.apply(@value).tap do |result|
raise J8::NilException if result.nil?
end
end
|
#get ⇒ Object
Also known as:
value
#if_present(consumer = nil, &block) ⇒ Object
60
61
62
63
64
65
|
# File 'lib/j8/optional.rb', line 60
def if_present(consumer = nil, &block)
callable = from_callable_class(consumer, block, J8::Consumer)
return unless present?
callable.accept(@value)
end
|
#map(function = nil, &block) ⇒ Object
71
72
73
74
75
76
|
# File 'lib/j8/optional.rb', line 71
def map(function = nil, &block)
callable = from_callable_class(function, block, J8::Function)
return J8::Optional.empty unless present?
J8::Optional.new(callable.apply(@value))
end
|
#or_else(value) ⇒ Object
78
79
80
81
82
83
84
|
# File 'lib/j8/optional.rb', line 78
def or_else(value)
if present?
@value
else
value
end
end
|
#or_else_get(supplier = nil, &block) ⇒ Object
86
87
88
89
90
91
92
93
94
95
96
|
# File 'lib/j8/optional.rb', line 86
def or_else_get(supplier = nil, &block)
callable = from_callable_class(supplier, block, J8::Supplier)
if present?
@value
else
callable.get.tap do |result|
raise J8::NilException if result.nil?
end
end
end
|
#or_else_raise(supplier = nil, &block) ⇒ Object
98
99
100
101
102
103
|
# File 'lib/j8/optional.rb', line 98
def or_else_raise(supplier = nil, &block)
callable = from_callable_class(supplier, block, J8::Supplier)
raise callable.get unless present?
@value
end
|
#present? ⇒ Boolean
67
68
69
|
# File 'lib/j8/optional.rb', line 67
def present?
!@value.nil?
end
|