我可以重载Groovy中的隐式类型转换吗? [英] Can I overload the implicit type conversions in Groovy?

查看:99
本文介绍了我可以重载Groovy中的隐式类型转换吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个函数

$ p $ def method1(MyClass2 mc2){...}

我用一个 MyClass1 类型的对象调用它。有没有一种方法可以指定如何隐式地从 MyClass1 转换为 MyClass2 ,以便方法调用可以工作而不必明确地说 method1(mc1 as MyClass2)

解决方案

如果MyClass1没有实现/扩展MyClass2,那么没有任何我知道的东西会在没有旧的备用Java方法重载的情况下执行as MyClass2转换。显式重载包含MyClass1签名的方法:

  def method1(MyClass1 mc1){
method1(mc1 as MyClass2 )
}

另一种更常用的替代方法是不显式键入method1,它不要求你有一个MyClass2实例:

  def method1(mc){
// do并让mc walk / talk / quack像MyClass2
//或者甚至可以在这个方法中使用as MyClass2,如果你需要它进一步下去的话。
}


Say I have a function

def method1(MyClass2 mc2) {...}

and I call it with an object of type MyClass1. Is there a way that I can specify how to implicitly convert from MyClass1 to MyClass2, so that the method call will work without having to explicitly say method1(mc1 as MyClass2)?

解决方案

If MyClass1 doesn't implement/extend MyClass2, there isn't anything that I'm aware of that'll do the "as MyClass2" conversion without the old standby Java method overloading. Explicitly overloading the method with the signature including MyClass1:

def method1(MyClass1 mc1) { 
    method1(mc1 as MyClass2)
}

The other, more groovy, alternative is to not explicitly type method1 so that it doesn't demand that you have an instance of MyClass2:

def method1(mc) {
    // do stuff and let mc walk/talk/quack like MyClass2
    // or even do the "as MyClass2" in this method if you need it for something further down.
}

这篇关于我可以重载Groovy中的隐式类型转换吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆