Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to specify a subset of type parameters in Scala, inferring the rest?

I have a class which looks like this:

class X[A <: Throwable, B, C](b: B, c: C)

A, B and C can be inferred, so I can just instantiate it with:

val x = new X(3, 4)

which gives me an X[Nothing, Int, Int] - often what I want.

but I sometimes want to specify A to be something other than Nothing (say AssertionError). Is this possible without also specifying B and C. I imagined syntax along the lines of:

val x = new X[AssertionError](3, 4)
val x = new X[AssertionError, _, _](3, 4)
val x = new X[AssertionError,,](3, 4)

but obviously this doesn't work.

Is there some syntax for this, or some way I can achieve the same result?

like image 923
Draemon Avatar asked Mar 01 '13 11:03

Draemon


People also ask

What is type inference in Scala?

The Scala compiler can infer the types of expressions automatically from contextual information. Therefore, we need not declare the types explicitly. This feature is commonly referred to as type inference. It helps reduce the verbosity of our code, making it more concise and readable.

What is .type in Scala?

Type declaration is a Scala feature that enables us to declare our own types. In this short tutorial, we'll learn how to do type declaration in Scala using the type keyword. First, we'll learn to use it as a type alias. Then, we'll learn to declare an abstract type member and implement it.

What is a type parameter Scala?

Language. Methods in Scala can be parameterized by type as well as by value. The syntax is similar to that of generic classes. Type parameters are enclosed in square brackets, while value parameters are enclosed in parentheses.


1 Answers

Here is my solution:

scala> class X[A <: Throwable, B, C](b: B, c: C)
defined class X

scala> class Builder[A <: Throwable] {
     |   def apply[B, C](b: B, c: C) = new X[A,B,C](b,c)
     | }
defined class Builder

scala> def X[A <: Throwable]: Builder[A] = new Builder[A]
X: [A <: Throwable]=> Builder[A]

scala> val x = X[AssertionError](3, 4)
x: X[AssertionError,Int,Int] = X@2fc709
like image 168
Eastsun Avatar answered Oct 15 '22 12:10

Eastsun