【问题标题】:How to define an impicit conversion from one to another existing type in Scala?如何在 Scala 中定义从一种到另一种现有类型的隐式转换?
【发布时间】:2011-12-08 13:51:11
【问题描述】:

假设我们在使用的库中有一个Foo 类,并且希望(在我们的代码文件中)Foo 实例在遇到Foo 实例时隐式转换为String 实例在某个地方需要String 实例。如何在 Scala 中实现这一点?

【问题讨论】:

    标签: scala types casting implicit enrich-my-library


    【解决方案1】:

    这样做:

    implicit def stringFromFoo(foo: Foo): String = foo.toString
    

    【讨论】:

    • 别忘了你需要导入这个方法或者把它放在编译器能找到它的地方(在超类或你的类的特征、包对象等中)。
    猜你喜欢
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多