scala - Why does scalac infer `Foo with Bar` not just `Foo` for match/case return type? -


in model class, have simple getter function so:

  def geoloc = {     geoquant match {       case "country" => country.find.byid(geolocid)       case "provice" => province.find.byid(geolocid.tolong)       case "city" => city.find.byid(geolocid.tolong)       case "street" => street.find.byid(geolocid.tolong)     }   } 

the idea being geolocation of object – can of either of 4 types. see, function geoloc has return type super class of all: country, province, city & street – extend model class.

instead function's return type model geoentity, geoentity trait each of these classes have along model.

why happen? can make function return specific types pattern matching?

scala infers specific type can. each of 4 instances both model , geoentity, that's inferred type: model geoentity. if want function return less specific type of model (all model geoentitys models, not models model geoentitys), annotate function type: def geoloc: model = ....

the function can have 1 return type , there's no way know @ compile time of 4 cases hit. if want return more specific type each case, information type object has needs part of object type (or use dependent typing, type information still has come somewhere). e.g. make object abstract generic type, subclasses specific instances:

class myobject[locationtype <: model] {   def geoloc: locationtype } class myobjectcountry extends myobject[country] {   def geoloc: country = ... } class myobjectprovice extends myobject[province] {   def geoloc: province = ... } 

Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -