简体   繁体   中英

Traits With implicit Class Scala

On my example. I want to find a way to use Implicit value in my connection to aws-sns.

object SNSClient {

}

class SNSClient {
  val region =
    try {
      val prop = new Properties()
      prop.load(new FileInputStream("config.properties"))
      prop.getProperty("aws.region")
    } catch {
      case e: Exception => println("error")
    }

 // In this method Scala wont compile
 def providesSNSClient(): AmazonSNS = {
      AmazonSNSClientBuilder
             .standard
             .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKey.toString(), secretKey.toString())))
             .withRegion(region) //Error compile
             .build()
  }
}

 /**
  * Rich prpierties
  */
 trait RegionsImplict {
   /**
    * Return default value if it does not provide Regions.EU_WEST_1
    */
   implicit class RegionB(region: String){
     def asRegion: Regions = Regions.values().find(_.name == region).getOrElse(Regions.EU_WEST_1)
   }

 }

So far so good I want to call my function asRegion on my line code .withRegion(region)//Error compile

The problem here is that region is NOT a String , so the implicit conversion doesn't kick in.

You can see this with the following simplified Scala REPL example:

scala> val region = try { "value" } catch { case e: Exception => println("error") }
region: Any = value  // <--- notice type is Any

Why? Because some of the code paths (ie the catch phrase) do not product a String, so the compiler has to "settle" for the closest common supertype, which is Any .

To fix this, you should either abort on exception, or provide some default value, otherwise some code paths simply won't produce a String. For example:

val region =
  try {
    val prop = new Properties()
    prop.load(new FileInputStream("config.properties"))
    prop.getProperty("aws.region")
  } catch {
    case e: Exception => println("error"); "us-east" // Default!
  }  

NOTE : as commented, it is not recommended to use implicit conversions so lightly, especially for common types such as Strings - they might kick in when you don't expect them to and make code harder to read.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM