【问题标题】:Scala implicits and type aliasesScala 隐式和类型别名
【发布时间】:2017-11-18 02:33:24
【问题描述】:

假设我有以下代码:

object Potato extends App {

  type CoolString = String
  type AwesomeString = String

  def potato(string: String)(implicit coolString: CoolString, awesomeString: AwesomeString) = {
    s"$string is a string. Oh, but don't forget - $coolString and also $awesomeString"
  }

  implicit val ice : CoolString = "Really Cold Ice"
  implicit val awe : AwesomeString = "Awe inspiring object"

  potato("Stringerino")

}

此代码因问题而失败

[error] ... ambiguous implicit values:
[error]  both value ice in object Potato of type => Potato.CoolString
[error]  and value awe in object Potato of type => Potato.AwesomeString
[error]  match expected type Potato.CoolString
[error]   potato("Stringerino")

这样使用隐式是不可能的吗?

【问题讨论】:

    标签: scala


    【解决方案1】:

    这样使用隐式是不可能的吗?

    不仅不可能,而且依赖这种将String 这样的通用类型作为隐含类型的方法是危险的。想一想,范围内的任何String 实例都将成为传递给该方法的合格候选者!

    类型别名只是一个类型别名,仅此而已。对于编译器来说,CoolString 和 AwesomeString 都只是 String。

    更好的方法是利用标记类型。例如,这是一个tagged type using shapeless:

    import shapeless.tag.@@
    
    trait CoolString
    trait AwesomeString
    
    type ReallyCoolString = String @@ CoolString
    type ReallyAwesomeString = String @@ AwesomeString
    

    然后:

    import shapeless.tag
    
    def potato(string: String)(implicit coolString: ReallyCoolString, awesomeString: ReallyAwesomeString) = {
      s"$string is a string. Oh, but don't forget - $coolString and also $awesomeString"
    }
    
    def main(args: Array[String]): Unit = {
      implicit val ice = tag[CoolString][String]("Really Cold Ice")
      implicit val awe = tag[AwesomeString][String]("Awe inspiring object")
    
      println(potato("Stringerino"))
    }
    

    产量:

    Stringerino is a string. 
    Oh, but don't forget - Really Cold Ice and also Awe inspiring object
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-29
      • 2017-01-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多