One of the most important parts of Scala is its strong type system. ScalaPy lets you continue using this even as you use dynamically-typed Python libraries by defining static type definitions.
Creating type definitions in ScalaPy is very similar to creating them with Scala.js. Type definitions are just annotated traits with methods defining what is available on the underlying Python value.
For example, we could define a static type definition for the built-in string type.
Once you have this type facade, it is usable with the
.as method just like converting to existing Scala types. So, to get a type-safe reference to the Python string we have loaded, we convert it to our facade type.
If we try to call this method with the wrong parameter type, we get the expected error message
When dealing with modules, ScalaPy offers an additional type
StaticModule that makes it possible to map a top-level Scala object to a Python module. For example, to create a static facade to the
string module we saw earlier, we can define a
Due to Python's dynamically typed nature, some APIs can have types that don't easily map to Scala constructs. To help with this, ScalaPy includes some special types to help defining static types for these situations easier.
ScalaPy includes the union type
py.| which can represent situations where one of two types is required. For example, the Python
Random class can be initialized with a seed that is an integer or a string. We could define a type facade as
And use it with either input type