简体   繁体   中英

Scala Internal Class Typing - Type Mismatch Error

I am experiencing a very strange typing error when running the below code.

The goal of this code is to have a class that can combine other instances of this class with itself, producing the updated instance. (Perhaps I should prefer immutability and return copies, but that's another discussion).

IntelliJ does not complain until I attempt to run the code, then it crashes with

type mismatch found: mic.MyInternalClass required: MyClass.this.MyInternalClass this.myVar =
this.myVar.combine(mic.myVar)"

IntelliJ Error Message

class MyClass(s: String) {

  var myVar: MyInternalClass = new MyInternalClass(s)

  def combine(mic: MyClass): MyClass = {

    this.myVar = this.myVar.combine(mic.myVar)
    this
  }

  class MyInternalClass(s: String) {

    var myInternalVar: String = s

    def combine(mic: MyInternalClass): MyInternalClass = {
      this.myInternalVar += mic.myInternalVar
      this
    }
  }
}


object App {


  def main(args : Array[String]) {

    var mc1: MyClass = new MyClass("dog")
    var mc2: MyClass = new MyClass("cat")

    mc1.combine(mc2)

    println(mc1.myVar.myInternalVar)
    println(mc2.myVar.myInternalVar)
  }

}

Each instance's MyInternalClass is considered a separate type in Scala, so you can't mix this 's and mic 's MyInternalClass . If that's not what you want, instead of using MyClass#MyInternalClass everywhere it's better to move MyInternalClass declaration to the companion object:

// otherwise you'll need to write MyClass.MyInternalClass explicitly even inside MyClass
import MyClass.MyInternalClass

class MyClass(s: String) {

  var myVar: MyInternalClass = new MyInternalClass(s)

  def combine(mic: MyClass): MyClass = {

    this.myVar = this.myVar.combine(mic.myVar)
    this
  }
}

object MyClass {
  class MyInternalClass(s: String) {

    var myInternalVar: String = s

    def combine(mic: MyInternalClass): MyInternalClass = {
      this.myInternalVar += mic.myInternalVar
      this
    }
  }
}

I just found this link: Referring to the type of an inner class in Scala

It looks like the inner class method needs a special type like so:

def combine(mic: MyClass#MyInternalClass): MyInternalClass = {

Still learning the nuances of why this is the case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM