kotlinname-collisionqualified-name

How to use "qualified this" with name clash?


I've got two classes from dependencies, let's call them both Demo, in package com.example.a and package com.example.b.

I want to create two extension functions in the same file to convert between the two Demo classes.

I need to reference the outer this in a scoped function.

I tried the following two solutions, but neither compiles:

1.

import com.example.a.Demo as DemoA
import com.example.b.Demo as DemoB

fun DemoA.toDemoB(): DemoB =
    foo {
       name = this@DemoA.name
    }

fun DemoB.toDemoA(): DemoA =
    foo {
        name = this@DemoB.name
    }
fun com.example.a.Demo.toDemoB(): com.example.b.Demo =
    foo {
       name = this@com.example.a.Demo.name
    }

fun com.example.a.Demo.toDemoA(): com.example.a.Demo =
    foo {
        name = this@com.example.b.Demo.name
    }

Solution

  • The qualified this doesn't specify the class name, it specifies the scope:

    fun DemoA.toDemoB(): DemoB = foo {
        name = this@toDemoB.name
    }
    
    fun DemoB.toDemoA(): DemoA = foo {
        name = this@toDemoA.name
    }
    

    In the first function, this@toDemoB refers to the receiver of the function toDemoB (that is a DemoA object). You could also use this@foo to refer to the inner scope, the parameter's receiver of the function foo.

    In the second function, this@toDemoA refers to the receiver of the function toDemoA (that is a DemoB object).

    There are no conflicts here.