Unable to override java.lang.String field. What is wrong?

前端 未结 1 769
北恋
北恋 2021-01-06 11:07

I tried to compile code that contains

class FixedIndexedRepository(override val name: java.lang.String, location: URI) extends FixedIndexedRepo
相关标签:
1条回答
  • 2021-01-06 11:39

    Rex says it is ugly:

    Making a public accessor from an inherited protected Java field

    Given:

    package j;
    
    public class HasName {
        protected String name = "name";
    }
    

    then the fake-out is:

    package user
    
    private[user] class HasNameAdapter extends j.HasName {
      protected def named: String = name
      protected def named_=(s: String) { name = s }
    }
    
    class User(n: String = "nom") extends HasNameAdapter {
      def name(): String = named
      def name_=(s: String) { this named_= s }
      this name_= n
    }
    
    object Test extends App {
      val u = new User("bob")
      Console println s"user ${u.name()}"
      Console println s"user ${u.name}"
    }
    

    You were forewarned about the ugly.

    I haven't quite worked out the details either, but the weekend is coming up.

    Unfortunately Scala 2.9.2 compiler stops with an error

    You mean, fortunately it stops with an error.

    0 讨论(0)
提交回复
热议问题