Genaric type parsing in Scala with default valueAbstract Types / Type Parameters in ScalaScala vs. Groovy vs. ClojureIs the Scala 2.8 collections library a case of “the longest suicide note in history”?Scala: Using HashMap with a default valueScala convert List[Int] to a java.util.List[java.lang.Integer]What are all the uses of an underscore in Scala?Scala Default Values: How do I get a default value from type Any in Scala while creating a LinkedList?default value for functions in parameters in ScalaFast and safe conversion from string to numeric typesHow to throw an exception from a recursive function in scala that returns Int
What was the motivation for the invention of electric pianos?
I was promised a work PC but still awaiting approval 3 months later so using my own laptop - Is it fair to ask employer for laptop insurance?
What next step can I take in solving this sudoku?
What 68-pin connector is this on my 2.5" solid state drive?
Interaction between Teferi Time Raveler and Enduring Ideal
Can derivatives be defined as anti-integrals?
Speedometer as a symbol into awesomebox
Make 2019 with single digits
Permutations in Disguise
Is there a real-world mythological counterpart to WoW's "kill your gods for power" theme?
What organs or modifications would be needed for a life biological creature not to require sleep?
Why does the speed of sound decrease at high altitudes although the air density decreases?
How to publish superseding results without creating enemies
Why is my fire extinguisher emptied after one use?
How do we know that black holes are spinning?
What are uses of the byte after BRK instruction on 6502?
Is there a tool to measure the "maturity" of a code in Git?
Some Prime Peerage
What made 4/4 time the most common time signature?
How do certain apps show new notifications when internet access is restricted to them?
Fasteners for securing cabinets together
How are unbalanced coaxial cables used for broadcasting TV signals without any problems?
Which is the current decimal separator?
POSIX compatible way to get user name associated with a user ID
Genaric type parsing in Scala with default value
Abstract Types / Type Parameters in ScalaScala vs. Groovy vs. ClojureIs the Scala 2.8 collections library a case of “the longest suicide note in history”?Scala: Using HashMap with a default valueScala convert List[Int] to a java.util.List[java.lang.Integer]What are all the uses of an underscore in Scala?Scala Default Values: How do I get a default value from type Any in Scala while creating a LinkedList?default value for functions in parameters in ScalaFast and safe conversion from string to numeric typesHow to throw an exception from a recursive function in scala that returns Int
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
I am looking for a Generic functional way to convert between Scala String to any numeric type. I need in case of failure to pass a default value.
For example, I need to convert from String to Int but in case the String to Int conversion failed. I need to pass a default value without having throws java.lang.NumberFormatException. I tried this way but doesn't get my idea as I need it generic and also with default value in case of exception
scala
add a comment
|
I am looking for a Generic functional way to convert between Scala String to any numeric type. I need in case of failure to pass a default value.
For example, I need to convert from String to Int but in case the String to Int conversion failed. I need to pass a default value without having throws java.lang.NumberFormatException. I tried this way but doesn't get my idea as I need it generic and also with default value in case of exception
scala
Do you want to specify the default by yourself, or do you always want a common default like zero or one?
– Luis Miguel Mejía Suárez
Mar 28 at 12:17
I need to add it by myself
– Sa2012
Mar 28 at 13:45
Given that I would go with Dima's answer, or something similar. A typeclass is always a good solution for this kind of problems.
– Luis Miguel Mejía Suárez
Mar 28 at 13:48
Actual, I was looking for a function to similar.toIntor.toDouble. But why typeclass is better solution? The solution related tosafeParsedo it correctly without any drawback.
– Sa2012
Mar 28 at 13:58
1
The typeclass under the hood is the same, the idea of the typeclass is that given that the transformation from String to Int is always the same, why would I need to specify it every time?
– Luis Miguel Mejía Suárez
Mar 28 at 14:04
add a comment
|
I am looking for a Generic functional way to convert between Scala String to any numeric type. I need in case of failure to pass a default value.
For example, I need to convert from String to Int but in case the String to Int conversion failed. I need to pass a default value without having throws java.lang.NumberFormatException. I tried this way but doesn't get my idea as I need it generic and also with default value in case of exception
scala
I am looking for a Generic functional way to convert between Scala String to any numeric type. I need in case of failure to pass a default value.
For example, I need to convert from String to Int but in case the String to Int conversion failed. I need to pass a default value without having throws java.lang.NumberFormatException. I tried this way but doesn't get my idea as I need it generic and also with default value in case of exception
scala
scala
edited Mar 28 at 10:54
Moustafa Mahmoud
1,0708 silver badges25 bronze badges
1,0708 silver badges25 bronze badges
asked Mar 28 at 10:43
Sa2012Sa2012
404 bronze badges
404 bronze badges
Do you want to specify the default by yourself, or do you always want a common default like zero or one?
– Luis Miguel Mejía Suárez
Mar 28 at 12:17
I need to add it by myself
– Sa2012
Mar 28 at 13:45
Given that I would go with Dima's answer, or something similar. A typeclass is always a good solution for this kind of problems.
– Luis Miguel Mejía Suárez
Mar 28 at 13:48
Actual, I was looking for a function to similar.toIntor.toDouble. But why typeclass is better solution? The solution related tosafeParsedo it correctly without any drawback.
– Sa2012
Mar 28 at 13:58
1
The typeclass under the hood is the same, the idea of the typeclass is that given that the transformation from String to Int is always the same, why would I need to specify it every time?
– Luis Miguel Mejía Suárez
Mar 28 at 14:04
add a comment
|
Do you want to specify the default by yourself, or do you always want a common default like zero or one?
– Luis Miguel Mejía Suárez
Mar 28 at 12:17
I need to add it by myself
– Sa2012
Mar 28 at 13:45
Given that I would go with Dima's answer, or something similar. A typeclass is always a good solution for this kind of problems.
– Luis Miguel Mejía Suárez
Mar 28 at 13:48
Actual, I was looking for a function to similar.toIntor.toDouble. But why typeclass is better solution? The solution related tosafeParsedo it correctly without any drawback.
– Sa2012
Mar 28 at 13:58
1
The typeclass under the hood is the same, the idea of the typeclass is that given that the transformation from String to Int is always the same, why would I need to specify it every time?
– Luis Miguel Mejía Suárez
Mar 28 at 14:04
Do you want to specify the default by yourself, or do you always want a common default like zero or one?
– Luis Miguel Mejía Suárez
Mar 28 at 12:17
Do you want to specify the default by yourself, or do you always want a common default like zero or one?
– Luis Miguel Mejía Suárez
Mar 28 at 12:17
I need to add it by myself
– Sa2012
Mar 28 at 13:45
I need to add it by myself
– Sa2012
Mar 28 at 13:45
Given that I would go with Dima's answer, or something similar. A typeclass is always a good solution for this kind of problems.
– Luis Miguel Mejía Suárez
Mar 28 at 13:48
Given that I would go with Dima's answer, or something similar. A typeclass is always a good solution for this kind of problems.
– Luis Miguel Mejía Suárez
Mar 28 at 13:48
Actual, I was looking for a function to similar
.toInt or .toDouble. But why typeclass is better solution? The solution related to safeParse do it correctly without any drawback.– Sa2012
Mar 28 at 13:58
Actual, I was looking for a function to similar
.toInt or .toDouble. But why typeclass is better solution? The solution related to safeParse do it correctly without any drawback.– Sa2012
Mar 28 at 13:58
1
1
The typeclass under the hood is the same, the idea of the typeclass is that given that the transformation from String to Int is always the same, why would I need to specify it every time?
– Luis Miguel Mejía Suárez
Mar 28 at 14:04
The typeclass under the hood is the same, the idea of the typeclass is that given that the transformation from String to Int is always the same, why would I need to specify it every time?
– Luis Miguel Mejía Suárez
Mar 28 at 14:04
add a comment
|
2 Answers
2
active
oldest
votes
Edit: I updated the solution to parse from any type to any type. This makes the solution more generic based on the question requested. I think you can use Scala functional way to have the generic type [T] but you need to split it into two parts.
First to implement parse types which parses from any type [U] to
any type [T]. parseTypes takes a function canBuildFrom as a parameter using Scala functional way. Then based on the output of this function you will checks if it parsed correctly or it has an exception. Also, in case it failed to parse you can pass a default parameter.
def parseTypes[T,U](str: U, canBuildFrom: U ⇒ T): Either[java.lang.NumberFormatException, T] =
Try(canBuildFrom(str)).map(Right(_)).getOrElse
Left(new java.lang.NumberFormatException(str.toString))
def safeParse[T,U](attributeValue: U, canBuildFrom: U ⇒ T, defaultValue: T): T =
parseTypes(attributeValue, canBuildFrom) match
case Right(x) ⇒ x
case Left(x) ⇒ defaultValue
case _ ⇒ defaultValue
def safeParseDoubleToBigDecimal(attributeValue: Double): BigDecimal = safeParse[BigDecimal,Double](attributeValue, toBigDecimal, 0.0)
You can use it to parse String to Int, Double, and Decimal as following:
def safeParseStringToInt(attributeValue: String): Int = safeParse[Int,String](attributeValue, _.toInt, 0)
def safeParseStringToDouble(attributeValue: String): Double = safeParse[Double ,String](attributeValue, _.toDouble, 0.0)
def safeParseStringToBigDecimal(attributeValue: String): BigDecimal = safeParse[BigDecimal ,String](attributeValue, BigDecimal(_), 0.0)
// example of usage
val x:Int = safeParseStringToInt("123",0)
val y:Int = safeParseStringToInt("aaa",0)
1
Thanks, this solve my problem. But Is there a way to convert from any generic to any generic?
– Sa2012
Mar 28 at 10:55
I think you can do the same and customize the function and the expected exception type.
– Moustafa Mahmoud
Mar 28 at 10:56
1
I like this solution as it seems to be simple and fit in my case.
– Sa2012
Mar 28 at 13:50
add a comment
|
This sort of thing is implemented really nice with typeclasses:
trait ParseIt[T]
protected def parse(s: String): T
def apply(s: String) = Try(parse(s)).toOption
implicit object ParseInt extends ParseIt[Int]
protected def parse(s: String) = s.toInt
implicit object ParseDouble extends ParseIt[Double]
protected def parse(s: String) = s.toDouble
// etc ...
def parse[T : ParseIt](s: String, orElse: => T) =
implicitly[ParseIt[T]](s).getOrElse(orElse)
val n: Int = parse("123", 0)
val d: Double = parse("123", 0.0)
nice solution - I pasted it in Scalafiddle - I had to addapplythat it worked:implicitly[ParseIt[T]].apply(s).getOrElse(orElse)- typo?
– pme
Mar 28 at 13:01
Nice solution! - But If I need to have specific value in case of some exception, How can I implement it?
– Sa2012
Mar 28 at 13:47
@Sa2012 Given the implementation, any exception will be catched by theTryinapply. Thus becoming aNone. Thus, being replaced by the default.
– Luis Miguel Mejía Suárez
Mar 28 at 13:50
If you care about the specific exception, you can just not convert the Try to an Option, and pattern match on the Exception.
– Ethan
Mar 28 at 19:50
add a comment
|
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55395593%2fgenaric-type-parsing-in-scala-with-default-value%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
Edit: I updated the solution to parse from any type to any type. This makes the solution more generic based on the question requested. I think you can use Scala functional way to have the generic type [T] but you need to split it into two parts.
First to implement parse types which parses from any type [U] to
any type [T]. parseTypes takes a function canBuildFrom as a parameter using Scala functional way. Then based on the output of this function you will checks if it parsed correctly or it has an exception. Also, in case it failed to parse you can pass a default parameter.
def parseTypes[T,U](str: U, canBuildFrom: U ⇒ T): Either[java.lang.NumberFormatException, T] =
Try(canBuildFrom(str)).map(Right(_)).getOrElse
Left(new java.lang.NumberFormatException(str.toString))
def safeParse[T,U](attributeValue: U, canBuildFrom: U ⇒ T, defaultValue: T): T =
parseTypes(attributeValue, canBuildFrom) match
case Right(x) ⇒ x
case Left(x) ⇒ defaultValue
case _ ⇒ defaultValue
def safeParseDoubleToBigDecimal(attributeValue: Double): BigDecimal = safeParse[BigDecimal,Double](attributeValue, toBigDecimal, 0.0)
You can use it to parse String to Int, Double, and Decimal as following:
def safeParseStringToInt(attributeValue: String): Int = safeParse[Int,String](attributeValue, _.toInt, 0)
def safeParseStringToDouble(attributeValue: String): Double = safeParse[Double ,String](attributeValue, _.toDouble, 0.0)
def safeParseStringToBigDecimal(attributeValue: String): BigDecimal = safeParse[BigDecimal ,String](attributeValue, BigDecimal(_), 0.0)
// example of usage
val x:Int = safeParseStringToInt("123",0)
val y:Int = safeParseStringToInt("aaa",0)
1
Thanks, this solve my problem. But Is there a way to convert from any generic to any generic?
– Sa2012
Mar 28 at 10:55
I think you can do the same and customize the function and the expected exception type.
– Moustafa Mahmoud
Mar 28 at 10:56
1
I like this solution as it seems to be simple and fit in my case.
– Sa2012
Mar 28 at 13:50
add a comment
|
Edit: I updated the solution to parse from any type to any type. This makes the solution more generic based on the question requested. I think you can use Scala functional way to have the generic type [T] but you need to split it into two parts.
First to implement parse types which parses from any type [U] to
any type [T]. parseTypes takes a function canBuildFrom as a parameter using Scala functional way. Then based on the output of this function you will checks if it parsed correctly or it has an exception. Also, in case it failed to parse you can pass a default parameter.
def parseTypes[T,U](str: U, canBuildFrom: U ⇒ T): Either[java.lang.NumberFormatException, T] =
Try(canBuildFrom(str)).map(Right(_)).getOrElse
Left(new java.lang.NumberFormatException(str.toString))
def safeParse[T,U](attributeValue: U, canBuildFrom: U ⇒ T, defaultValue: T): T =
parseTypes(attributeValue, canBuildFrom) match
case Right(x) ⇒ x
case Left(x) ⇒ defaultValue
case _ ⇒ defaultValue
def safeParseDoubleToBigDecimal(attributeValue: Double): BigDecimal = safeParse[BigDecimal,Double](attributeValue, toBigDecimal, 0.0)
You can use it to parse String to Int, Double, and Decimal as following:
def safeParseStringToInt(attributeValue: String): Int = safeParse[Int,String](attributeValue, _.toInt, 0)
def safeParseStringToDouble(attributeValue: String): Double = safeParse[Double ,String](attributeValue, _.toDouble, 0.0)
def safeParseStringToBigDecimal(attributeValue: String): BigDecimal = safeParse[BigDecimal ,String](attributeValue, BigDecimal(_), 0.0)
// example of usage
val x:Int = safeParseStringToInt("123",0)
val y:Int = safeParseStringToInt("aaa",0)
1
Thanks, this solve my problem. But Is there a way to convert from any generic to any generic?
– Sa2012
Mar 28 at 10:55
I think you can do the same and customize the function and the expected exception type.
– Moustafa Mahmoud
Mar 28 at 10:56
1
I like this solution as it seems to be simple and fit in my case.
– Sa2012
Mar 28 at 13:50
add a comment
|
Edit: I updated the solution to parse from any type to any type. This makes the solution more generic based on the question requested. I think you can use Scala functional way to have the generic type [T] but you need to split it into two parts.
First to implement parse types which parses from any type [U] to
any type [T]. parseTypes takes a function canBuildFrom as a parameter using Scala functional way. Then based on the output of this function you will checks if it parsed correctly or it has an exception. Also, in case it failed to parse you can pass a default parameter.
def parseTypes[T,U](str: U, canBuildFrom: U ⇒ T): Either[java.lang.NumberFormatException, T] =
Try(canBuildFrom(str)).map(Right(_)).getOrElse
Left(new java.lang.NumberFormatException(str.toString))
def safeParse[T,U](attributeValue: U, canBuildFrom: U ⇒ T, defaultValue: T): T =
parseTypes(attributeValue, canBuildFrom) match
case Right(x) ⇒ x
case Left(x) ⇒ defaultValue
case _ ⇒ defaultValue
def safeParseDoubleToBigDecimal(attributeValue: Double): BigDecimal = safeParse[BigDecimal,Double](attributeValue, toBigDecimal, 0.0)
You can use it to parse String to Int, Double, and Decimal as following:
def safeParseStringToInt(attributeValue: String): Int = safeParse[Int,String](attributeValue, _.toInt, 0)
def safeParseStringToDouble(attributeValue: String): Double = safeParse[Double ,String](attributeValue, _.toDouble, 0.0)
def safeParseStringToBigDecimal(attributeValue: String): BigDecimal = safeParse[BigDecimal ,String](attributeValue, BigDecimal(_), 0.0)
// example of usage
val x:Int = safeParseStringToInt("123",0)
val y:Int = safeParseStringToInt("aaa",0)
Edit: I updated the solution to parse from any type to any type. This makes the solution more generic based on the question requested. I think you can use Scala functional way to have the generic type [T] but you need to split it into two parts.
First to implement parse types which parses from any type [U] to
any type [T]. parseTypes takes a function canBuildFrom as a parameter using Scala functional way. Then based on the output of this function you will checks if it parsed correctly or it has an exception. Also, in case it failed to parse you can pass a default parameter.
def parseTypes[T,U](str: U, canBuildFrom: U ⇒ T): Either[java.lang.NumberFormatException, T] =
Try(canBuildFrom(str)).map(Right(_)).getOrElse
Left(new java.lang.NumberFormatException(str.toString))
def safeParse[T,U](attributeValue: U, canBuildFrom: U ⇒ T, defaultValue: T): T =
parseTypes(attributeValue, canBuildFrom) match
case Right(x) ⇒ x
case Left(x) ⇒ defaultValue
case _ ⇒ defaultValue
def safeParseDoubleToBigDecimal(attributeValue: Double): BigDecimal = safeParse[BigDecimal,Double](attributeValue, toBigDecimal, 0.0)
You can use it to parse String to Int, Double, and Decimal as following:
def safeParseStringToInt(attributeValue: String): Int = safeParse[Int,String](attributeValue, _.toInt, 0)
def safeParseStringToDouble(attributeValue: String): Double = safeParse[Double ,String](attributeValue, _.toDouble, 0.0)
def safeParseStringToBigDecimal(attributeValue: String): BigDecimal = safeParse[BigDecimal ,String](attributeValue, BigDecimal(_), 0.0)
// example of usage
val x:Int = safeParseStringToInt("123",0)
val y:Int = safeParseStringToInt("aaa",0)
edited Apr 4 at 13:16
answered Mar 28 at 10:52
Moustafa MahmoudMoustafa Mahmoud
1,0708 silver badges25 bronze badges
1,0708 silver badges25 bronze badges
1
Thanks, this solve my problem. But Is there a way to convert from any generic to any generic?
– Sa2012
Mar 28 at 10:55
I think you can do the same and customize the function and the expected exception type.
– Moustafa Mahmoud
Mar 28 at 10:56
1
I like this solution as it seems to be simple and fit in my case.
– Sa2012
Mar 28 at 13:50
add a comment
|
1
Thanks, this solve my problem. But Is there a way to convert from any generic to any generic?
– Sa2012
Mar 28 at 10:55
I think you can do the same and customize the function and the expected exception type.
– Moustafa Mahmoud
Mar 28 at 10:56
1
I like this solution as it seems to be simple and fit in my case.
– Sa2012
Mar 28 at 13:50
1
1
Thanks, this solve my problem. But Is there a way to convert from any generic to any generic?
– Sa2012
Mar 28 at 10:55
Thanks, this solve my problem. But Is there a way to convert from any generic to any generic?
– Sa2012
Mar 28 at 10:55
I think you can do the same and customize the function and the expected exception type.
– Moustafa Mahmoud
Mar 28 at 10:56
I think you can do the same and customize the function and the expected exception type.
– Moustafa Mahmoud
Mar 28 at 10:56
1
1
I like this solution as it seems to be simple and fit in my case.
– Sa2012
Mar 28 at 13:50
I like this solution as it seems to be simple and fit in my case.
– Sa2012
Mar 28 at 13:50
add a comment
|
This sort of thing is implemented really nice with typeclasses:
trait ParseIt[T]
protected def parse(s: String): T
def apply(s: String) = Try(parse(s)).toOption
implicit object ParseInt extends ParseIt[Int]
protected def parse(s: String) = s.toInt
implicit object ParseDouble extends ParseIt[Double]
protected def parse(s: String) = s.toDouble
// etc ...
def parse[T : ParseIt](s: String, orElse: => T) =
implicitly[ParseIt[T]](s).getOrElse(orElse)
val n: Int = parse("123", 0)
val d: Double = parse("123", 0.0)
nice solution - I pasted it in Scalafiddle - I had to addapplythat it worked:implicitly[ParseIt[T]].apply(s).getOrElse(orElse)- typo?
– pme
Mar 28 at 13:01
Nice solution! - But If I need to have specific value in case of some exception, How can I implement it?
– Sa2012
Mar 28 at 13:47
@Sa2012 Given the implementation, any exception will be catched by theTryinapply. Thus becoming aNone. Thus, being replaced by the default.
– Luis Miguel Mejía Suárez
Mar 28 at 13:50
If you care about the specific exception, you can just not convert the Try to an Option, and pattern match on the Exception.
– Ethan
Mar 28 at 19:50
add a comment
|
This sort of thing is implemented really nice with typeclasses:
trait ParseIt[T]
protected def parse(s: String): T
def apply(s: String) = Try(parse(s)).toOption
implicit object ParseInt extends ParseIt[Int]
protected def parse(s: String) = s.toInt
implicit object ParseDouble extends ParseIt[Double]
protected def parse(s: String) = s.toDouble
// etc ...
def parse[T : ParseIt](s: String, orElse: => T) =
implicitly[ParseIt[T]](s).getOrElse(orElse)
val n: Int = parse("123", 0)
val d: Double = parse("123", 0.0)
nice solution - I pasted it in Scalafiddle - I had to addapplythat it worked:implicitly[ParseIt[T]].apply(s).getOrElse(orElse)- typo?
– pme
Mar 28 at 13:01
Nice solution! - But If I need to have specific value in case of some exception, How can I implement it?
– Sa2012
Mar 28 at 13:47
@Sa2012 Given the implementation, any exception will be catched by theTryinapply. Thus becoming aNone. Thus, being replaced by the default.
– Luis Miguel Mejía Suárez
Mar 28 at 13:50
If you care about the specific exception, you can just not convert the Try to an Option, and pattern match on the Exception.
– Ethan
Mar 28 at 19:50
add a comment
|
This sort of thing is implemented really nice with typeclasses:
trait ParseIt[T]
protected def parse(s: String): T
def apply(s: String) = Try(parse(s)).toOption
implicit object ParseInt extends ParseIt[Int]
protected def parse(s: String) = s.toInt
implicit object ParseDouble extends ParseIt[Double]
protected def parse(s: String) = s.toDouble
// etc ...
def parse[T : ParseIt](s: String, orElse: => T) =
implicitly[ParseIt[T]](s).getOrElse(orElse)
val n: Int = parse("123", 0)
val d: Double = parse("123", 0.0)
This sort of thing is implemented really nice with typeclasses:
trait ParseIt[T]
protected def parse(s: String): T
def apply(s: String) = Try(parse(s)).toOption
implicit object ParseInt extends ParseIt[Int]
protected def parse(s: String) = s.toInt
implicit object ParseDouble extends ParseIt[Double]
protected def parse(s: String) = s.toDouble
// etc ...
def parse[T : ParseIt](s: String, orElse: => T) =
implicitly[ParseIt[T]](s).getOrElse(orElse)
val n: Int = parse("123", 0)
val d: Double = parse("123", 0.0)
answered Mar 28 at 12:05
DimaDima
27.9k3 gold badges27 silver badges46 bronze badges
27.9k3 gold badges27 silver badges46 bronze badges
nice solution - I pasted it in Scalafiddle - I had to addapplythat it worked:implicitly[ParseIt[T]].apply(s).getOrElse(orElse)- typo?
– pme
Mar 28 at 13:01
Nice solution! - But If I need to have specific value in case of some exception, How can I implement it?
– Sa2012
Mar 28 at 13:47
@Sa2012 Given the implementation, any exception will be catched by theTryinapply. Thus becoming aNone. Thus, being replaced by the default.
– Luis Miguel Mejía Suárez
Mar 28 at 13:50
If you care about the specific exception, you can just not convert the Try to an Option, and pattern match on the Exception.
– Ethan
Mar 28 at 19:50
add a comment
|
nice solution - I pasted it in Scalafiddle - I had to addapplythat it worked:implicitly[ParseIt[T]].apply(s).getOrElse(orElse)- typo?
– pme
Mar 28 at 13:01
Nice solution! - But If I need to have specific value in case of some exception, How can I implement it?
– Sa2012
Mar 28 at 13:47
@Sa2012 Given the implementation, any exception will be catched by theTryinapply. Thus becoming aNone. Thus, being replaced by the default.
– Luis Miguel Mejía Suárez
Mar 28 at 13:50
If you care about the specific exception, you can just not convert the Try to an Option, and pattern match on the Exception.
– Ethan
Mar 28 at 19:50
nice solution - I pasted it in Scalafiddle - I had to add
apply that it worked: implicitly[ParseIt[T]].apply(s).getOrElse(orElse) - typo?– pme
Mar 28 at 13:01
nice solution - I pasted it in Scalafiddle - I had to add
apply that it worked: implicitly[ParseIt[T]].apply(s).getOrElse(orElse) - typo?– pme
Mar 28 at 13:01
Nice solution! - But If I need to have specific value in case of some exception, How can I implement it?
– Sa2012
Mar 28 at 13:47
Nice solution! - But If I need to have specific value in case of some exception, How can I implement it?
– Sa2012
Mar 28 at 13:47
@Sa2012 Given the implementation, any exception will be catched by the
Try in apply. Thus becoming a None. Thus, being replaced by the default.– Luis Miguel Mejía Suárez
Mar 28 at 13:50
@Sa2012 Given the implementation, any exception will be catched by the
Try in apply. Thus becoming a None. Thus, being replaced by the default.– Luis Miguel Mejía Suárez
Mar 28 at 13:50
If you care about the specific exception, you can just not convert the Try to an Option, and pattern match on the Exception.
– Ethan
Mar 28 at 19:50
If you care about the specific exception, you can just not convert the Try to an Option, and pattern match on the Exception.
– Ethan
Mar 28 at 19:50
add a comment
|
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55395593%2fgenaric-type-parsing-in-scala-with-default-value%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Do you want to specify the default by yourself, or do you always want a common default like zero or one?
– Luis Miguel Mejía Suárez
Mar 28 at 12:17
I need to add it by myself
– Sa2012
Mar 28 at 13:45
Given that I would go with Dima's answer, or something similar. A typeclass is always a good solution for this kind of problems.
– Luis Miguel Mejía Suárez
Mar 28 at 13:48
Actual, I was looking for a function to similar
.toIntor.toDouble. But why typeclass is better solution? The solution related tosafeParsedo it correctly without any drawback.– Sa2012
Mar 28 at 13:58
1
The typeclass under the hood is the same, the idea of the typeclass is that given that the transformation from String to Int is always the same, why would I need to specify it every time?
– Luis Miguel Mejía Suárez
Mar 28 at 14:04