Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type problems with native Java classes

Tags:

java

types

scala

I have the following problem, maybe someone can help me (or explain, where my mistake is). Given are a trait and a class:

trait TextAttr[T <: {def setText(s:String); def getText : String}] {
  val obj : T
  def txt_= (s:String) = obj.setText(s)
  def txt = obj.getText
}

class ScalaText {
  private var t = ""
  def setText(s:String) = t = s
  def getText = t
}

Now I create a new class using both of them:

class ScalaTextUser extends TextAttr[ScalaText] {
  override val obj = new ScalaText
}

That's okay. But if I want to create something like that with the class org.eclipse.swt.widgets.Text (or any other pure Java class) I get an error. Here the code:

class SwtTextUser(parent:Composite) extends TextAttr[Text] {
  override val obj = new Text(parent, 0)
}

And this is the error:

type arguments [org.eclipse.swt.widgets.Text] do not conform to trait TextAttr's type parameter bounds [T <: AnyRef{def setText(String): Unit; def getText: String}]

Has anybody an idea?

Thanks, Chris.


1 Answers

Try changing the trait declaration to the following:

trait TextAttr[T <: {def setText(s: String); def getText(): String}] {

Scala has a subtly-different treatment for methods with and without parentheses. When in doubt, add the parens and let the compiler sort things out.

like image 180
Daniel Spiewak Avatar answered Jul 28 '26 04:07

Daniel Spiewak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!