16
16
17
17
package com .ckkloverdos .convert
18
18
19
- import com .ckkloverdos .maybe .Maybe
20
19
import Converter .AnyConverter
20
+ import select .ConverterSelectionStrategy
21
+ import com .ckkloverdos .maybe ._
21
22
22
23
/**
23
24
* An immutable registry for converters.
24
25
*
25
26
* @author Christos KK Loverdos <loverdos@gmail.com>.
26
27
*/
27
- trait Converters extends CanConvert {
28
- def converters : Vector [AnyConverter ]
28
+ class Converters (selector : ConverterSelectionStrategy ) extends CanConvert {
29
+ def canConvertType (sm : Converter .AnyManifest , tm : Converter .AnyManifest ) = {
30
+ selector.find(sm, tm).isJust
31
+ }
29
32
30
- def converterFor [S : Manifest , T : Manifest ](sm : Manifest [S ], tm : Manifest [T ], cacheResult : Boolean = true ): Maybe [Converter [S , T ]]
33
+ def findConverter [S : Manifest , T : Manifest ](sm : Manifest [S ], tm : Manifest [T ]): Maybe [Converter [S , T ]] = {
34
+ selector.find(sm, tm).asInstanceOf [Maybe [Converter [S , T ]]]
35
+ }
36
+
37
+ /**
38
+ * Converts a value or throws an exception if the value cannot be converted.
39
+ */
40
+ @ throws(classOf [ConverterException ])
41
+ def convertValueEx [S : Manifest , T : Manifest ](sourceValue : S , tm : Manifest [T ]): T = {
42
+ val sm = manifest[S ]
43
+ findConverter(sm, tm) match {
44
+ case Just (cv) =>
45
+ cv.convertEx(sourceValue)
46
+ case NoVal =>
47
+ ConverterException (" Could not find converter from %s -> %s for value %s" , sm, tm, sourceValue)
48
+ case Failed (exception, explanation) =>
49
+ ConverterException (exception, " Error [%s] trying to find converter from %s -> %s for value %s" , explanation, sm, tm, sourceValue)
50
+ }
51
+ }
31
52
32
53
def convertValue [S : Manifest , T : Manifest ](sourceValue : S , tm : Manifest [T ]): Maybe [T ] = {
33
- (for (converter <- converterFor (manifest[S ], tm))
54
+ (for (converter <- findConverter (manifest[S ], tm))
34
55
yield converter.convert(sourceValue)).flatten1
35
56
}
57
+
58
+ def convertValueToInt [S : Manifest ](sourceValue : S ): Maybe [Int ] = convertValue(sourceValue, Manifest .Int )
59
+ def convertValueToLong [S : Manifest ](sourceValue : S ): Maybe [Long ] = convertValue(sourceValue, Manifest .Long )
60
+ def convertValueToBoolean [S : Manifest ](sourceValue : S ): Maybe [Boolean ] = convertValue(sourceValue, Manifest .Boolean )
36
61
}
0 commit comments