Terry Grosso
Terry Grosso

Reputation: 241

typealias from a lib : Unresolved Reference

I got an Unresolved Reference for a typeAlias I use from my library. Everything works fine in local, but when using the imported released library I got this error.

Anyone had this issue already please ? Here is my code :

sealed class CountingRequestResult<ResultT> {
   data class Progress<ResultT>(
           val progressFraction: Double
   ) : CountingRequestResult<ResultT>()

   data class Completed<ResultT>(
           val result: ResultT
   ) : CountingRequestResult<ResultT>() 
} 

typealias AttachmentUploadRemoteResult = CountingRequestResult<UploadUserDocumentResponse>

Upvotes: 2

Views: 587

Answers (1)

lior_13
lior_13

Reputation: 609

Kotlin, like other programming languages, lets you define a type alias for other existing types. For instance, we can use them to attach more context to an otherwise general type, like naming type String as UserName or Password:

typealias UserName = String
typealias Password = String
fun checkUserName(userName: UserName) {
    // some code here
}
fun checkPassword(password: Password) {
    // some code here
}

Type aliases are merely artifacts of the source code. Therefore, they’re not introducing any new types at runtime. For instance, every place where we’re using a UserName instance, the Kotlin compiler translates it to a String:

$ kotlinc TypeAlias.kt

$ javap -c -p com.example.alias.TypeAliasKt
Compiled from "TypeAlias.kt"
public final class com.example.alias.TypeAliasKt {
  public static final void checkUserName(java.lang.String);
  // truncated
}

Therefore, in local everything works as expected, but building a library results in losing the aliasing, hence: Unresolved Reference.

In your project using the lib, you can define the same alias name. However I will say that it is not such a good idea. Making a change in the lib's alias will not be changed in the project's alias and also you won't be warned in cases such parsing from or to Json. A better approach will be using a data class. For instance:

data class UserName(val userName: String)

And that class will be defined in both lib and project.

Upvotes: 1

Related Questions