我正在努力解决Scala隐式转换问题.以下代码段说明了我的问题:
import org.junit.{ Test, Before, After };
class ImplicitsTest {
implicit def toStringWrapper(str: String) = new StringWrapper(str);
@Test
def test(){
val res1: Predicate = "str" startsWith "other";
}
}
class StringWrapper(str: String){
def startsWith(other: String): Predicate = null;
}
trait Predicate
Run Code Online (Sandbox Code Playgroud)
如何通过隐式转换toStringWrapper强制String文字"str"转换为startsWith返回Predicate而不是Boolean?
代码示例无法编译.我知道String已经有一个startsWith方法,我只想使用另一个方法,我认为使用隐式转换可能是一种方法.
Rex*_*err 12
Scala谢天谢地不会让你在没有注意的情况下偷偷替换替换方法 - 如果你在一个类上调用一个方法,并且该类有这个方法,那就是你得到的方法调用.否则可能会引起各种混乱.
这将为您提供另外两个选项:(1)重命名方法(2)添加特定方法进行转换.
第二种方法的工作原理如下:您定义了一个类,它既包含您想要的方法,又包含一个返回自身的唯一命名方法,如果您希望能够使用自定义,则可以选择从该类隐式转换回字符串像原始字符串一样的项目(好像它有扩展字符串):
object ImplicitExample {
class CustomString(s: String) {
def original = s
def custom = this
def startsWith(other: String): Int = if (s.startsWith(other)) 1 else 0
}
implicit def string_to_custom(s: String) = new CustomString(s)
implicit def custom_to_string(c: CustomString) = c.original
def test = {
println("This".custom.startsWith("Thi"))
println("This".custom.length())
}
}
scala> ImplicitExample.test
1
4
scala>
Run Code Online (Sandbox Code Playgroud)