masterdany88
masterdany88

Reputation: 5341

Cast and instance of in scala view template in playFramework

I am looping over collection of Person in scala view in PlayFramework2.2.6. Person class is superclass for classes User,Contact.

While looping I would like to access some parameters specified for extending classes like email attribute in User class.

Here is model's classes:

public class Person {
  int id;
  String name;
  Date date;
}
public class User extends Person {
  String email;
  String login;
  String password;
}
public class Contact extends Person {
  Address address;
}

public class Customer {
  List<Person> persons;


  // AND NOW I WOULD LIKE TO DO THIS IN SCALA TEMPLATE


  public void print() {
    for(Person person: this.persons) {
      if(person instanceof User) {}
        System.out.println(((User)person).email);
      }
  }
}

view layer:

@for(person <- persons) {
  @if(person instanceOf User) {
     @((User)person).email
  }
}

But I am getting an error:

value instanceOf is not a member of models.Person

Please give me some help on:

in Scala template/view layer of PlayFramework. Thanks.

Upvotes: 1

Views: 965

Answers (2)

Callum
Callum

Reputation: 879

Use pattern matching:

@for(person <- persons) {
  @person match {
    case _ : User => {@{_.email}}  
    case _ => {@{}}
  }
}

This will look cleaner if you ever need to make an "If type of Contact" condition

Upvotes: 1

Mikesname
Mikesname

Reputation: 8901

The Scala/Twirl equivalents should be:

To verify instance type:

person.isInstanceOf[User] // bool?

To cast:

person.asInstanceOf[User] // User instance

Upvotes: 6

Related Questions