简体   繁体   中英

convert datasnaphot from Java to Kotlin

I'm at the beginning of Kotlin so I want to convert this part of code:

Query query = reference.child("users");

query.addValueEventListener(new ValueEventListener() {

    public void onDataChange(DataSnapshot dataSnapshot) {
        Users users = null;

        for (DataSnapshot d: dataSnapshot.getChildren()) {
            users = d.getValue(Users.class);

            if (users.getEmail().equals(mail)) {
              photoUri = users.getPhotos();
              nameSurname = users.getNome() + " " + users.getCognome();
              break;
            }
        }

        if (photoUri != null) {
            Glide.with(MainActivity.this)
                 .load(photoUri)
                 .transform(new CircleTransform(MainActivity.this))
                 .into(profile);
        }
        else {
            Glide.with(MainActivity.this)
                 .load(graphic)  
                 .transform(new CircleTransform(MainActivity.this))
                 .into(profile);
        }
    }

    public void onCancelled(DatabaseError databaseError) {
    }

});

to Kotlin. So I've made this code:

class DataReferenceService @Inject constructor(private var auth: FirebaseDatabase) 
        : MainContract.DatabaseRepository,ValueEventListener {

    var mail: String? = null

    override fun getImageProfile(mail: String?) {
        this.mail = mail
        val query = auth.reference.child("users")
        query.addValueEventListener(this)
    }

    override fun onCancelled(p0: DatabaseError?) {
    }

    override fun onDataChange(data: DataSnapshot?) {
        var user: User? = null

        data?.children?.forEach {
            child -> getPhotos(child)
        }
    }

    fun getPhotos(child: DataSnapshot) {
        val user = child.getValue(User.class) // name expected, why ???
    }
}

the problem is indicate in comment, why it does not convert it? Is there an other way to do it? I want to use takeIf{} but I don't understand how to use it.

Thanks

The equivalent of Java's User.class is User::class.java in Kotlin.

Documentation about this here .

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