In Scala, you can use pattern matching to produce a result depending on the type of the input. For instance:
val title = content match {
case blogPost: BlogP
In order to ensure total pattern matching, you would need to build the function into the type itself. Here's how I'd do it:
public abstract class Content
{
private Content() { }
public abstract T Match(Func convertBlog, Func convertPost);
public class Blog : Content
{
public Blog(string title)
{
Title = title;
}
public string Title { get; private set; }
public override T Match(Func convertBlog, Func convertPost)
{
return convertBlog(this);
}
}
public class BlogPost : Content
{
public BlogPost(string title, Blog blog)
{
Title = title;
Blog = blog;
}
public string Title { get; private set; }
public Blog Blog { get; private set; }
public override T Match(Func convertBlog, Func convertPost)
{
return convertPost(this);
}
}
}
public static class Example
{
public static string GetTitle(Content content)
{
return content.Match(blog => blog.Title, post => post.Blog.Title + ": " + post.Title);
}
}