score:6
as you might know, if you have a parameter of type foo[a]
, then you can make the method generic in just a
:
def dostuff[a](p: foo[a]): a = ???
since that might not always be the case, we can try to use an implicit parameter that can express the relationship between a
and b
. since we can't only apply some of the generic parameters to a method call (generic parameter inference is all or nothing), we have to split this into 2 calls. this is an option:
case class stuff[b <: foo[_]]() {
def get[a](p: param)(implicit ev: b => foo[a]): a = ???
}
you can check the types in the repl:
:t stuff[intfoo].get(new param) //int
:t stuff[stringfoo].get(new param) //string
another option along the same lines, but using an anonymous class, is:
def stuff[b <: foo[_]] = new {
def apply[a](p: param)(implicit ev: b <:< foo[a]): a = ???
}
:t stuff[intfoo](new param) //int
here, i've used apply
in stead of get
, so you can apply the method more naturally. also, as suggested in your comment, here i've used <:<
in the evidence type. for those looking to learn more about this type of generalized type constraint, you can read more here.
you might also consider using abstract type members instead of generic parameters here. when struggling with generic type inference, this often provides an elegant solution. you can read more about abstract type members and their relationship to generics here.
score:7
another option is to use type members:
sealed trait foo {
type value
def value: value
}
case class stringfoo(value: string) extends foo { type value = string }
case class intfoo(value: int) extends foo { type value = int }
def dostuff[b <: foo](p: any): b#value = ???
// hypothetical invocation
val i: int = dostuff[intfoo](param)
val s: string = dostuff[stringfoo](param)
note that both solutions mainly work around the syntactic restriction in scala, that you cannot fix one type parameter of a list and have the compiler infer the other.
Source: stackoverflow.com
Related Query
- How can I write a function have a polymorphic return type based on the type argument of its type parameter?
- Rectangle Class (objects) can have two intrinsic parameters length and width. How to write (independent) function to calculate the area?
- Why do I have to write down the return type of the anonymous function in fold
- How to declare tuple as the return type of a function and how to access tuple in caller code in scala?
- How can I write a recursive polymorphic function with Shapeless
- How can a method accept a (T <: Seq)[A] and return T[B] -- the same type of sequence with a different type parameter?
- Scala: How do I write the type of the function that sortBy takes?
- How to get the proper return type when using a filter based on type in Scala
- How can I return two DStreams in a function after using the filter transformation in spark streaming?
- In Scala, how to summon a polymorphic function applicable to an input type, without knowing the output type or full type arguments?
- How to preserve argument type of polymorphic function in return type
- How to specify the return type of a function to be a (arbitrary) monad?
- How to tell to the compiler a function can only return subtype of a trait and not the trait itself?
- Scala: How to make the return type of function generic and dependent on runtime arguments?
- How to write a function that returns something of the type `=> Int`?
- Is it possible to define a function return type based on a defined mapping from the type of a function argument?
- How can I check that method parameters have the same type as the methods this?
- How can I define a function to accept all the types which extend a common base type (Scala, specific code below)?
- how can I write a function in scala called Order that takes one arguement: a list of Ints. And returns the same List of Ints from least to greatest
- I have a function which takes an implicit parameter. How can I pass the parameter implicitly using implicit parameters of an instance of some class?
- How can I explicitly tell the compiler what the return type is?
- i have wriiten a logout code in welcome.scala.html page but getting errors in that page how can i write the code for it
- How can I call a Scala function taking a PartialFunction with a Unit return type from Java?
- Given an input List(1,2,3,4,5), write a a function that can be passed onto flatMap, and return the result List(1,2,2,3,3,4,4,5)
- How are Scala collections able to return the correct collection type from a map operation?
- How to define a function whose output type depends on the input type
- How can I obtain the default value for a type in Scala?
- How do I write a JSON Format for an object in the Java library that doesn't have an apply method?
- How to use the function type in scala within defined in type meaningfully?
- How to write a zipWith method that returns the same type of collection as those passed to it?
More Query from same tag
- How can I limit my query by date using ScalaQuery
- How to click on the DASHBOARD tab to switch to it in the same webpage
- Concatenate two Scala mutable maps preserving the keys of the first map
- drop,dropRight,take,takeRight vs substring?
- Permanently hidden warning from Scalac parsing Java code - compiler bug?
- Getting sub-scores for sub-queries in Lucene
- From RDD of array of arrays into dataframe
- How does Array.toList work in Scala?
- Spark orc reading string as decimal value
- Get Cluster_ID and the rest of table using Spark MLlib KMeans
- Scala + Lift + REST - Returning Arrays with serveJx
- Scala Parser: but it is neither contained in the delimiters list, nor in the reserved keyword list of lexical
- How can I pass a variable into a DataFrame.selectExpr
- Akka DistributedPubSubMediator at-least-once delivery guarantees for publishing to a topic
- How can I create an additional ExecutionContext that has similar properties to ExecutionContext.global?
- Is it possible to create a secondary constructor without a macro annotation in Scala?
- Scala requires String: Question about Scala generics
- value not found in Terminated method in akka actor example
- Call Super Constructor
- Return Try or Future As Generic Container
- Pattern matching generic case classes for compiler
- How to implement types like MapK in Scala 3 / Dotty?
- Spark Scala: "cannot resolve symbol saveAsTextFile (reduceByKey)" - IntelliJ Idea
- How to control TCP_NODELAY setting for Scala remote actor?
- How to achieve the expression simplification with distributivity rule in Scala?
- Trying to understand how classes declared on the REPL are treated internally
- This parallelized sum program, using divide-and-conquer, does not terminate
- difference between action and action.async
- How to determine if `this` is an instance of a class or an object?
- SBT: compile & package -- "working tree not clean"