Scala 是否可以在匹配情况下使用隐式函数?
我有这样的枚举Scala 是否可以在匹配情况下使用隐式函数?,scala,implicit,Scala,Implicit,我有这样的枚举 object SortCountryField extends Enumeration { type SortCountryField = Value val countryName = Value("country_name") val countryStatus = Value("country_status") } 我在match case中使用这个SortCountryFieldenum。 在这里,我每次都需要转换为字符串 为了方便起见,
object SortCountryField extends Enumeration {
type SortCountryField = Value
val countryName = Value("country_name")
val countryStatus = Value("country_status")
}
我在match case
中使用这个SortCountryField
enum。
在这里,我每次都需要转换为字符串
为了方便起见,我尝试使用隐式
转换器从SortCountryField.{Value}
然而,当我在下面的匹配案例中使用隐式函数时,我最终出现了一个编译器错误
'myString' match{
case SortCountryField.countryName.toString => //Some operations
case SortCountryField.countryStatus.toString => //another operation
}
错误日志:-
found : mypackage.ConstantUtils.SortCountryField.Value
[error] required: String
[error] case SortCountryField.countryStatus => //my-operations
我认为您最好在比赛中使用enum,如:
SortCountryField withName <your_string> match {
case SortCountryField.countryName => //Some operations
case SortCountryField.countryStatus => //another operation
}
我认为您最好在比赛中使用enum,如:
SortCountryField withName <your_string> match {
case SortCountryField.countryName => //Some operations
case SortCountryField.countryStatus => //another operation
}
您还可以执行以下操作:
'myString' match{
case x if x == SortCountryField.countryName.toString => //Some operations
case x if x == SortCountryField.countryStatus.toString => //another operation
}
您还可以执行以下操作:
'myString' match{
case x if x == SortCountryField.countryName.toString => //Some operations
case x if x == SortCountryField.countryStatus.toString => //another operation
}
隐式转换器是什么样子的?
我猜您有converter
SortCountryField=>String
,但您需要SortCountryField.Value=>String
转换器。您的隐式转换器是什么样子的?
我猜您有converter
SortCountryField=>String
,但您需要SortCountryField.Value=>String
转换器。在枚举中添加以下函数:
implicit def toString(value: Value): String = value.toString
在匹配中使用以下选项:
val countryStaus:String = SortCountryField.countryStatus
'myString' match {
case `countryStatus` => //Some operations
case _ => // Another operation
}
在枚举中添加以下函数:
implicit def toString(value: Value): String = value.toString
在匹配中使用以下选项:
val countryStaus:String = SortCountryField.countryStatus
'myString' match {
case `countryStatus` => //Some operations
case _ => // Another operation
}
如何在Try中包装不匹配的字符串?我的意思是,我不知道怎么写,我是scala。我已经用使用
Try
的代码更新了答案。我们如何在Try中包装不匹配的字符串?我的意思是,我不知道怎么写,我是scala。我已经用Try
更新了答案。