Error that function does not exist although it exists


#1

when i try to call a function on an object i get the error that the function does not exist, allthough it exists. i have following class

    class WrapperDto (dto : AbstractDto){

    val type = dto::class.simpleName
    val dto = dto
    fun isTypeOf(dto: KClass<InitDto>) : Boolean {
        return type == dto::class.simpleName
    }
}

and try to call the method isTypeOf like this later

client.onmessage = fun(wrapperDto: WrapperDto){
    try{
        println("trying to get the type type of the dto generated by a json string")
        val typeOf = wrapperDto.isTypeOf(InitDto::class)         
        println("success")
    } catch (e : Exception){
        writeMessage("error")
    }
}

but get following error:

trying to get the type of the dto generated by a json string
main$lambda	(anonymous function)	Uncaught TypeError: wrapperDto.isTypeOf_d8ukon$ is not a function

in intellij the code is not marked as error, and the function exists, so why do i get this error


#2

@Richard could you please provide a self-contained example?
I can’t reproduce it with

import kotlin.reflect.KClass

class WrapperDto (dto : AbstractDto){

    val type = dto::class.simpleName
    val dto = dto
    fun isTypeOf(dto: KClass<InitDto>) : Boolean {
        return type == dto::class.simpleName
    }
}
open class AbstractDto
class InitDto : AbstractDto()

fun main(args: Array<String>) {
    val wrapperDto = WrapperDto(InitDto())
    try{
        println("trying to get the type type of the dto generated by a json string")
        val typeOf = wrapperDto.isTypeOf(InitDto::class)         
        println("success")
    } catch (e : Exception){
        println("error")
    }
}

BTW, you can declare val dto in primary constructor, like:

class WrapperDto (val dto : AbstractDto){
...

#3

it simply seems that when i retrive a kotlin js object from a json string, it only has its values but not the functions anymore (unlike gson).

here is my person class

class Person() : AbstractDto() {
    var firstName = ""
    var familyName = ""   
    fun getFullName(): String {
        if (this.firstName != "" && this.familyName != "") {
            return this.firstName + " " + familyName
        }
        if(this.firstName != ""){
            return this.firstName
        }
        return familyName
    }
}

when i run this code

println("start test")
val personDto = Person()
personDto.firstName = "first"
personDto.familyName = "family"
val sPersonDto = JSON.stringify(personDto)
val personDto2 = JSON.parse<Person>(sPersonDto)
val fullName = personDto2.getFullName()
println("success")

i just see the message “start test” in the console and following error message:

(anonymous function)	(anonymous function)	Uncaught TypeError: personDto2.getFullName is not a function

#4

It works as expected. JSON can’t fully serialize and deserialize objects even JS objects. To get more info see MDN reference.