scala 继承java,Scala和Java-隐式参数和继承

The following code gives an error:

package test

trait Base {

def method:String

}

trait Trait extends Base {

def method()(implicit i:String):String = { "2" }

}

object Object extends Trait {

}

The error is "object creation impossible, since method method in class Base of type => String is not defined"

The above error is fixed by following code

package test

trait Base {

def method:String

}

trait Trait extends Base {

def method:String = method()("String") // Over loading

def method()(implicit i:String):String = { "2" }

}

object Object extends Trait {

}

Now instead of Scala class, when I define a Java interface as follows:

// Java Code

package test;

public interface JBase {

String method();

}

// Scala Code

package test

trait Trait extends JBase {

def method:String = method()("10")

def method()(implicit i:String):String = { "2" }

}

object Object extends Trait {

}

I get an error "ambiguous reference to overloaded definition, both method method in trait Trait of type ()(implicit i: String)String and method method in trait Trait of type ()String match argument types ()"

What is the difference in both these scenarios that makes the compiler behave differently? How do I solve this issue?

解决方案

Here's an example that I think shows clearly what is going on:

object Test extends App {

class A { def f(): String = "x" }

class B extends A { override def f: String = "y" }

class C { def f: String = "z" }

println { (new A).f() } // OK

println { (new B).f() } // OK

println { (new C).f() } // FAILS

}

A: Has parentheses, called with parentheses, everything good.

B: Has no parentheses, but supertype does have parentheses, so still good. This corresponds to your case.

C: Has no parentheses, called with parentheses, no good.

Basically, Java methods are always considered "with parentheses", so, Trait's supertype has the parentheses, so using parentheses in method()("string") is insufficient to clarify which method you mean.

edit: Honestly I think you are better off renaming the method. Even in the case where there is no ambiguity, the behavior could be quite surprising:

trait Trait {

def method: String = method()("x")

def method()(implicit i: String): String = i

}

val t = new Trait { }

implicit val s = "y"

println { t.method }

> "x"

println { t.method() }

> "y"

Furthermore, the fact that the name is the same isn't buying you anything in terms of polymorphism: only the non-implicit method overrides Base.method -- it's just an aesthetic decision to make the names be the same.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值