From ec61d98c47782114889fc27a97ac0c2c9dd895d3 Mon Sep 17 00:00:00 2001 From: noti0na1 Date: Fri, 28 Nov 2025 14:37:19 +0100 Subject: [PATCH] Handling nullable types in convertTo for adapting number constants to target number types [Cherry-picked 5a3828354b347a0bd19695979e37060afd4a24b5] --- .../src/dotty/tools/dotc/core/Constants.scala | 3 ++- tests/pos/i24571.scala | 24 +++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 tests/pos/i24571.scala diff --git a/compiler/src/dotty/tools/dotc/core/Constants.scala b/compiler/src/dotty/tools/dotc/core/Constants.scala index 63acfbe55701..959c677b143f 100644 --- a/compiler/src/dotty/tools/dotc/core/Constants.scala +++ b/compiler/src/dotty/tools/dotc/core/Constants.scala @@ -3,6 +3,7 @@ package dotc package core import Types.*, Symbols.*, Contexts.* +import NullOpsDecorator.stripNull import printing.Printer import printing.Texts.Text @@ -149,7 +150,7 @@ object Constants { /** Convert constant value to conform to given type. */ def convertTo(pt: Type)(using Context): Constant | Null = { - def classBound(pt: Type): Type = pt.dealias.stripTypeVar match { + def classBound(pt: Type): Type = pt.dealias.stripTypeVar.stripNull() match { case tref: TypeRef if !tref.symbol.isClass && tref.info.exists => classBound(tref.info.bounds.lo) case param: TypeParamRef => diff --git a/tests/pos/i24571.scala b/tests/pos/i24571.scala new file mode 100644 index 000000000000..7b5180acc20f --- /dev/null +++ b/tests/pos/i24571.scala @@ -0,0 +1,24 @@ +val n: Byte = 2 +val n2: Byte | Null = 2 +val n3: Int = 2 +val n4: Int | Null = 2222 +val n5: Int | Byte = 2 +val n6: Byte | Int = 10000 + +val x: Option[Byte] = Option(2) +val x2: Option[Byte] = Option[Byte](2) +val x3: Option[Int] = Option(2) +val x4: Option[Null] = Option(null) +val x5: Option[Byte | Null] = Option(2) + +trait MyOption[+T] + +object MyOption: + def apply[T](x: T | Null): MyOption[T] = ??? + def applyOld[T](x: T): MyOption[T] = ??? + +val test1: MyOption[Byte] = MyOption(2) +val test2: MyOption[Byte] = MyOption.applyOld(2) +val test3: MyOption[Int] = MyOption(2) +val test4: MyOption[Null] = MyOption(null) +val test5: MyOption[Byte | Null] = MyOption(2)